Code readability & style basics

Computer Science · Software engineering

Question 1 of 10

0

    A magic number is:

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Code readability & style basics explained

    Code readability is how easily a person can understand what a program does. Clear names, consistent style, small functions and comments that explain why the code exists make code easier to read, change and debug.

    Programs are read far more often than they are written, by teammates and by the original author months later. Readable code therefore saves time whenever it is changed.

    Useful habits include:

    • Descriptive names: use total_price rather than tp, and avoid names that hide their meaning.
    • Named constants: replace a bare number such as 1.21 with a name such as vat_rate that explains where it comes from.
    • Short functions: each function should do one clear job.
    • Consistent style: follow the indentation, spacing and naming rules of the project. Many languages have formatters that apply the rules automatically.
    • Useful comments: explain why a decision was made, not what the next line obviously does.

    Style rules are conventions. Their main value is consistency across a codebase, so that readers do not have to learn a new pattern in every file.

    Worked example

    A hypothetical shop adds a 21% tax to a price. Compare two versions.

    total = price * 1.21
    
    vat_rate = 0.21
    total = price * (1 + vat_rate)
    
    1. Both compute the same value. For a price of 50, 50×1.21=60.550 \times 1.21 = 60.5.
    2. The second version says what 1.21 means, and a change of rate needs one edit instead of a search for every 1.21 in the code.

    Check: 1+0.21=1.211 + 0.21 = 1.21, so the two versions always give the same result.

    What you will practise

    104 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • Readable code:
    • Good variable names:
    • Comments should explain:
    • Consistent indentation:
    • Refactoring means:
    • A magic number is:
    • Naming a constant MAX_RETRIES instead of writing 5 inline mainly improves:
    • Using whitespace and blank lines in code mainly helps:

    …and 96 more.