Menu

Defensive Design

Maintainability

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.

Techniques that improve maintainability

  • Sub programs split a long program into named tasks. Each task is written once and called by name, so the main program reads like a short list of steps, and a change to that task only has to be made in one place.
  • Naming conventions mean choosing names that describe the value stored, such as 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.
  • Indentation shows which lines belong inside an 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.
  • Comments are notes beginning with # 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.

Practise this