05. Naming and decomposition — Homework solutions

These problems have more than one right answer. Don't match these words exactly — aim for names and steps a stranger could understand. Treat them as a yardstick, not a key.

Problem 1 — Rename the mystery

Problem. Replace four useless names so the program reads clearly.

How to think about it. Read the maths. a times b looks like a count times a price; adding 100 looks like a flat fee. Name each value for what it means.

A good rewrite.

local quantity = 3
local price_each = 250
local subtotal = quantity * price_each
local total = subtotal + 100
print(total)

It prints 850 — the cost of 3 items at 250 each, plus a flat fee of 100.

Common mistakes.

  • Naming by type — number_a, number_b. No better than a and b. Name by meaning.
  • Renaming only some. If even one name stays a mystery, the reader is still guessing.

Problem 2 — Chop the chore

Problem. Break a big job into five to eight short, named steps.

Sample answer for get ready for school:

  1. Get out of bed.
  2. Wash face and brush teeth.
  3. Get dressed.
  4. Eat breakfast.
  5. Pack the school bag.
  6. Put on shoes and coat.
  7. Leave the house.

What makes it good. You can picture every line in one second. None is "do the morning stuff" — too big to trust.

Problem 3 — Name the steps as functions

Problem. Turn three of your steps into word_word names.

Sample answer, using three steps above:

  • Eat breakfasteat_breakfast
  • Pack the school bagpack_bag
  • Put on shoes and coatput_on_shoes

What makes it good. Each name is a short verb-plus-thing. If a step needs three or four words to name, it was probably more than one step.

Challenge — Two-level breakdown

Problem. Break a job into four big steps, then break one of those into three smaller steps.

Sample answer for run a small birthday party:

  • Before
  • Food
    • Lay out the plates and cups.
    • Bring out the savoury snacks.
    • Bring out the cake at the right moment.
  • Games
  • After

What makes it good. The three sub-steps sit under Food, not under the whole party. That nesting — a big step made of smaller steps — is the shape of every real program: a whole made of parts, each part made of smaller parts.

Done?

That is the end of Part 1. You've learned what a program is, how to plan one on paper, the three patterns every program is built from, how to trace code by hand, and how to name and break down a problem. The Part 1 mini-project ties these planning skills into one flowchart. After that, you finally install Lua and write real code.