Improving a working program

Programming guides

A program can work correctly and still be difficult to understand. Improving its structure without changing its intended behaviour is called refactoring. You might choose a clearer name or put repeated steps into a function.

First make it work. Then make it easier to read. Save a working version before making a change so you have something to compare with.

Organize your instructions

Imagine rewriting a long recipe so all the steps for making the sauce sit together. The meal should stay the same, but the recipe becomes easier to follow.

In code, a function can group steps that have a useful shared purpose. You do not need to create a function for every single line. Choose groups whose names explain the job they do.

Give a repeated job a name

Suppose your program repeatedly adds coins and stars, with each star worth three points. We can describe that calculation once:

# language: en
function calculateScore(coins, stars):
    return coins + stars * 3
say calculateScore(2, 4)
say calculateScore(5, 1)

The parameters coins and stars receive the values for one call. return sends the calculated number back. The function does not print anything itself; the calling say displays each result.

Predict, then run

Use the scoring rule to calculate both answers on paper.

14
8

Those are the results that the earlier repeated calculations should also have produced. Keeping the same answers is part of checking a refactor.

Your challenge

Add a call for zero coins and zero stars. Then choose an even clearer function name if you can, updating both its declaration and calls. Check all three results afterwards.

A common mistake

Changing the rule while reorganizing the code makes it harder to know why an answer changed. Making stars worth five points is a new game rule, not just a refactor. Do that as a separate change with new expected results.

Shorter code is not always clearer code. Prefer names and steps that you can explain aloud. A helpful comment explains a reason, such as why stars are worth extra points, instead of repeating every instruction in words.

Where next?

Functions · Clear names · Testing