Defensive Design
Maintainability is a measure of how straightforward a program is to follow, put right and extend later on. A maintainable program can be picked up months later by the person who wrote it, or by a completely different programmer, and changed without a struggle.
Programs are rarely finished. Errors are found after release, users ask for new features and rules change, so the code you write today will probably be edited many times. If only the original author can follow the code, every change is risky: a small fix can break something else because nobody can see how the parts fit together. Maintainability is about the shape of the code, not about testing it.
price_per_student rather than p. A meaningful name saves the reader from tracing back through the code to work out what a variable holds, and one consistent style makes the whole program look familiar.if, elif, else, for or while, so the structure of the program can be seen at a glance. It matters most where blocks are nested and the reader has to work out which lines belong to which construct.# that explain what a section does, or the reasoning behind a choice. The translator ignores them, so they are written for people. A good comment explains the purpose of the code; a comment that simply repeats the line beneath it adds nothing.# works out the total price of a trip
def trip_total(students, price_each):
return students * price_each
student_count = int(input("How many students? "))
price_per_student = float(input("Price per student in pounds? "))
total = trip_total(student_count, price_per_student)
print("Trip total: " + str(total))Output when the user types 24, 12.5:
How many students? 24
Price per student in pounds? 12.5
Trip total: 300.0
This program is easy to maintain because the calculation sits in a sub program named trip_total, the variables say what they store, the body is indented and a short comment explains what the sub program is for. Another programmer could change the pricing rule by editing one line.
OCR GCSE Computer Science · Defensive Design