Night 27: Tidy code
Vous avez déjà terminé cette soirée, en Python ou en pseudocode. Elle compte pour les deux. Entraînez-vous à nouveau si vous le souhaitez.
Tonight: tidy code
- Week 4 is about your pet's world. Before you build the final project, tidy up!
- You will learn one thing: how to write clean code that people can read.
Words for tonight
| Word | Meaning |
|---|---|
| tidy | in order; easy to find things |
| constant | a value that never changes while the program runs |
| comment | a note for people, after //; the computer does not run it |
Good names
| Messy | Tidy |
|---|---|
A ← 3 |
SnacksPerDay ← 3 |
INPUT X |
INPUT PetName |
FUNCTION F(N : INTEGER) |
FUNCTION Double(N : INTEGER) |
- A name should say what the value is. Cambridge style joins words with capitals:
SnacksPerDay.
Constants
- A value that never changes is a
CONSTANT. In 9618 you write it with=.
CONSTANT MaxEnergy = 10
DECLARE Energy : INTEGER
Energy ← 4
OUTPUT "Energy: ", Energy, " of ", MaxEnergy
- To change it later, you change one line.
Comments explain why
// The pet sleeps 8 hours, and each hour gives 1 energy.
CONSTANT SleepHours = 8
DECLARE Energy : INTEGER
Energy ← 2
Energy ← Energy + SleepHours // wake up rested
OUTPUT Energy
- Do not explain what each line does: good names do that. Explain why.
Do not repeat yourself
- The same lines again and again? Write a procedure, and use a loop.
PROCEDURE Greet(Name : STRING)
OUTPUT "Good night, " & Name & "!"
ENDPROCEDURE
CALL Greet("Kit")
CALL Greet("Lumi")
- Tidy code has fewer mistakes, because each idea is written only once.
Difficulté 1/5 · 100 pièces + un petit bonus lors de la première réussite aujourd'hui
This code works, but A et B say nothing. Rename A à SnacksPerDay et B à Days everywhere. The output stays 12.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 2/5 · 140 pièces + un petit bonus lors de la première réussite aujourd'hui
Make a constant MaxEnergy with the value 10. Write EnergyLeft(Used : INTEGER) RETURNS INTEGER, which returns MaxEnergy - Used. Use the constant, not the number 10.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 2/5 · 140 pièces + un petit bonus lors de la première réussite aujourd'hui
The starter repeats one line three times. Write Greet(Name : STRING), which outputs Good night, Kit! for Kit. Then call it in a loop over the array Names.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 3/5 · 200 pièces + un petit bonus lors de la première réussite aujourd'hui
Write Clamp(Value : INTEGER) RETURNS INTEGER. It keeps energy on the scale: below 0 gives 0, above MaxEnergy gives MaxEnergy, anything else stays the same.
Cliquez sur Exécuter pour voir le résultat ici.