DoAssignment study guide

A4.3 · Document program code to a clear standard

Learn to document program code to a clear standard through clear examples and targeted practice.

Ontario Grade 12 Computer Science

Programming Concepts and Skills

ICS4U A4.3 • Making code understandable to its intended readers

In ICS3U, you learned to read and write programs using variables, selection, iteration, and methods or functions. A4.3 focuses on documenting program code to a clear standard. Documentation is information that helps a reader understand what code is for and how to use or change it. It includes meaningful names and consistent formatting as well as written comments. It should explain what is not already obvious, and it must agree with what the program actually does. In this lesson, the small Python examples are read-only teaching examples; their expected results are traced from the code, not reported as program runs.

What you will learn

  • Explain how documentation helps a reader understand and maintain a program.
  • Choose useful names, comments, and formatting for a stated audience.
  • Document a function's purpose, inputs, assumptions, and expected result.
  • Review documentation for clarity, accuracy, and consistency with the code.

1. Start with the reader and purpose

Before adding documentation, consider who needs to read the code: you later, a classmate, or someone responsible for maintaining it. A clear standard is a consistent set of choices that makes the program understandable to that audience. A short classroom program may need less explanation than a program another person must reuse, but both benefit from clear names and orderly layout.
Useful documentation answers practical questions. What is the code for? What information does it receive? What does it produce or change? Are there assumptions a user must meet? What parts of the code need explanation because their purpose is not apparent? These questions help keep documentation relevant rather than adding comments to every line.
A function header or docstring can summarize purpose, inputs, assumptions, and result. Keep the description consistent with the code. If the function is changed, its documentation should be reviewed too. A description that once was accurate can become misleading after an edit.
  • Write for a reader who may not know why the code was created.
  • Describe purpose, inputs, assumptions, and expected result when they help a reader use the code.
  • Documentation must be revised when program behaviour changes.

2. Use names and layout as documentation

A descriptive identifier often communicates more than a comment. For example, `total` says less than `subtotal_before_tax` when the latter is the value being stored. Use names that distinguish the roles of values and functions. Avoid names that are so long or vague that they slow the reader down. Follow one naming style consistently within the project.
Formatting also makes structure visible. Indentation shows which statements belong inside a function, loop, or conditional. Blank lines can separate related parts. Consistent spacing and layout help readers scan code and notice where one task ends and another begins. The particular style can vary; consistency matters more than mixing several styles.
Comments are most useful when they explain purpose, a non-obvious choice, or an assumption. A comment that merely restates the next line gives little extra information. For example, `count = count + 1` beside `# add one to count` is usually unnecessary. If a value has a less obvious meaning, explaining that meaning may help. Keep comments brief, accurate, and close to the code they describe.
  • Choose names that make the role of a value or function clear.
  • Use consistent indentation and spacing to show program structure.
  • Use comments to add context, not to repeat obvious instructions.

3. Document a function and review it

A function description should help a reader decide whether and how to use the function. State what it does, what each input represents, any preconditions, and what result to expect. A precondition is something that must be true before the function is used. Do not claim that the function handles cases that its code does not handle.
Review documentation alongside the code. Read the description, then trace the function using a small example: do the stated inputs match the parameters, and does the stated result follow from the statements? Also check whether names and comments are consistent, whether formatting is steady, and whether any comment has become outdated. This is a reading and editing process, not proof that the program has been executed or fully tested.
Use the smallest amount of explanation that makes the code clear to its intended reader. Too little leaves important assumptions hidden; too much can bury the program in repeated or outdated statements. If a comment and the code disagree, correct the documentation or the code so that the intended behaviour is clear.
  • State input meaning, preconditions, and expected result when relevant.
  • Check the description against a trace of the actual code.
  • Remove or revise comments that are inaccurate, redundant, or outdated.

Worked example

Improve a function description

A function receives a number of minutes and returns the number of whole hours in that amount. Document its purpose and input, identify its precondition, and trace the result for 185 minutes.

Python 3

def whole_hours(minutes):
    """Return whole hours in non-negative whole minutes.

    Precondition: minutes is a non-negative integer.
    """
    return minutes // 60
  1. Set a useful contract
    The purpose is to return whole hours, not to convert minutes into a decimal number of hours. The input should be a non-negative whole number of minutes. The description should say that the result discards any remaining minutes.
  2. Trace the supplied input
    For 185 minutes, integer division by 60 gives 3 whole hours. The remainder is not returned, so the expected output is 3.
    185//60=3185 // 60 = 3
Answer: A suitable description is: “Return the number of whole hours in a non-negative whole number of minutes. Input: minutes, a non-negative integer. Result: whole hours; remaining minutes are discarded.”
Check: The description distinguishes whole hours from a decimal conversion and states the assumption needed for the input.

Worked example

Replace a comment that only repeats code

A classmate writes a function that counts values above a chosen limit. Improve the documentation so it explains the function's purpose and inputs rather than narrating obvious operations. Trace the result for [4, 9, 6] with a limit of 5.

Python 3

def count_above(values, limit):
    """Return how many values are greater than limit.

    Inputs: values, a list of numbers; limit, a number.
    """
    count = 0
    for value in values:
        if value > limit:
            count += 1
    return count
  1. Describe the task
    The function takes a list of numbers and a limit, then returns how many list values are greater than the limit. A comment such as “increase count” merely repeats an operation. A purpose description gives the reader more useful information.
  2. Trace each value
    The value 4 is not greater than 5; 9 is greater; and 6 is greater. The count therefore increases twice. The expected output is 2.
    0+1+1=20 + 1 + 1 = 2
Answer: Document the function as counting values strictly greater than the limit. The list and limit are its inputs; the returned integer is the count. The trace gives an expected result of 2.
Check: The word “strictly” matters: a value equal to the limit would not be counted.

Worked example

Check documentation against a change

A function originally returned the first name in a list, but it has been changed to return the last name. Show how to bring its documentation into agreement and trace the changed version for ["Mina", "Owen", "Pia"].

Python 3

def last_name(names):
    """Return the last item in a non-empty list of names.

    Precondition: names contains at least one item.
    """
    return names[-1]
  1. Find the mismatch
    A description that still says “first name” no longer matches code that selects the final list item. Leaving it unchanged could lead a reader to use the function incorrectly.
  2. Update and trace
    The documented purpose should say that the function returns the last name in a non-empty list. The stated precondition is important because selecting the last item requires at least one item. In the supplied list, the last item is Pia, so that is the expected result.
Answer: Update the function description and any related comments to say “last name,” and state that the input list must not be empty. The expected output for the supplied list is “Pia.”
Check: The description now matches the selected list position, and the precondition explains when that selection is valid.

Common mistakes and how to avoid them

Commenting every line by restating its operation.
Correction: Explain purpose, assumptions, or a non-obvious choice; allow clear code to speak for itself.
Using a comment that describes an earlier version of the code.
Correction: Review and update documentation whenever the program's behaviour changes.
Leaving input assumptions unstated.
Correction: State preconditions when they affect whether a function can be used as described.
Treating inconsistent formatting as a personal preference that cannot affect readability.
Correction: Choose a simple style and apply it consistently so readers can recognize structure.

Lesson summary

  • Clear code documentation serves its intended reader and explains purpose and important assumptions.
  • Meaningful names and consistent formatting are part of making code understandable.
  • Comments should add useful context rather than repeat obvious statements.
  • Trace examples and compare documentation with code to catch mismatches and outdated claims.

Check your understanding

Question 1

A comment says “returns the smallest score,” but the function selects the largest score. What is the best documentation action?
  1. Leave the comment because the function's name is clear.
  2. Correct the comment or the code so the documented and actual behaviour agree.
  3. Add the same comment beside every statement.
  4. Remove all names from the function to avoid confusion.
Show answer and explanation
Correct the comment or the code so the documented and actual behaviour agree.
Documentation must describe the behaviour the code actually has. Resolve the mismatch rather than preserving a misleading description.

Question 2

Which comment adds the most useful information to a loop that adds each price to a running total?
  1. “Add price to total” beside the addition statement.
  2. “The total is a number” beside every line.
  3. A brief note explaining that the prices are being accumulated before a later summary is displayed.
  4. A note claiming the loop is correct without explaining its purpose.
Show answer and explanation
A brief note explaining that the prices are being accumulated before a later summary is displayed.
The purpose of the accumulation gives context that the individual addition statement may not show. The other choices repeat code or make an unsupported claim.

Question 3

A function returns the final element of a list. Which precondition should its documentation state?
  1. The list must contain at least one element.
  2. The list must contain exactly ten elements.
  3. Every element must be a whole number.
  4. The list must be sorted.
Show answer and explanation
The list must contain at least one element.
A final element can be selected only when the list is non-empty. The other conditions are not required by this stated behaviour.

Key terms

Documentation
Information in or alongside code that helps readers understand its purpose, use, assumptions, or structure.
Comment
A written note in source code that is intended to explain or clarify the code for a reader.
Precondition
A condition that must be true before a function or part of a program is used.
Trace
A step-by-step reading of how values and instructions produce an expected result.

Continue through ICS4U

View the complete ICS4U Ontario Grade 12 Computer Science curriculum and lessons

Tutor support for A4.3 · Document program code to a clear standard

Working on A4.3 · Document program code to a clear standard in ICS4U? Bring the question and your own attempt. In a live session, you can trace a small input step by step, compare expected and actual output, and test an edge case. Ask about the first step that does not make sense, then try a similar question yourself.

Explore coding tutoring · Request an eligible free 30-minute introduction. Your request is matched by subject and language; a tutor must accept before a time is confirmed.

برای مبحث A4.3 · مستندسازی روشن کد برنامه در درس ICS4U، سؤال و تلاش خود را همراه بیاورید. در جلسه می‌توانید یک ورودی کوچک را گام‌به‌گام دنبال کنید، خروجی مورد انتظار و واقعی را مقایسه کنید و یک حالت مرزی را بیازمایید. راهنمای معلم برنامه‌نویسی را ببینید یا جلسهٔ معارفهٔ رایگان ۳۰ دقیقه‌ای درخواست کنید. زمان جلسه پس از پذیرش معلم قطعی می‌شود.

About this lesson and its review

Published by DoAssignment. This reviewed lesson follows Ontario Grade 12 Computer Science (ICS4U), expectation A4.3. It is a study resource, not an official curriculum publication.

Before publication, content is checked for structure, mathematical or chemical notation, calculations, course boundaries, and readability. Errors can still occur, so corrections are welcomed.

Official curriculum reference

Report a correction or ask a question