Chapter 4 · Design and Code
Writing Maintainable Code
- Page 13 of 18
- 18 min read
Code that works is only the first step. ClinicQueue will be changed many times: new services, a second clinic, the AI reminder text. Each change starts with someone reading the existing code and working out what it does. If that takes an hour of puzzling for every ten minutes of changing, the team slows down, and every change risks breaking something nobody understood. Maintainable code is code that another person (or you, months later) can read, understand and change safely.
On the previous page, Data Modelling with Entity–Relationship Diagrams, you designed the data ClinicQueue stores. This page is about the code on top of it. You will take one messy, working Python function from Farhan's first prototype and improve it step by step, checking after each step that the output stays exactly the same. All patient data is invented.
What you will learn
- What makes code readable: names, small functions with one job, and clear control flow.
- How to write comments and docstrings that explain why, and how to avoid comments that lie.
- What a style guide such as PEP 8 is for, and what formatters and linters do.
- How to refactor a messy function in small, safe steps, proving the output does not change.
- The basics of input validation and error handling, and why magic numbers and duplication cause bugs.
Readable code
Here is the function Farhan wrote in the first week to print the front-desk queue for a day and the reminder SMS lines. It works. Read it and try to say what it does before you read the output.
Example:
appointments = [
("Ayesha Khan", "09:30", "2026-11-10", "booked", "01700000001"),
("Rafi Ahmed", "09:00", "2026-11-10", "booked", ""),
("Mim Akter", "10:00", "2026-11-10", "cancelled", "01700000003"),
("Joseph Das", "09:15", "2026-11-10", "booked", "01700000004"),
("Sara Islam", "09:00", "2026-11-11", "booked", "01700000005"),
]
def proc(l, t):
# loop
r = []
c = 0
for x in l:
if x[2] == t:
if x[3] != "cancelled":
if x[4] == "":
p = "no phone"
else:
p = x[4]
r.append(x[1] + " " + x[0] + " (" + p + ")")
c = c + 1 # add 1 to c
r.sort()
for i in r:
print(i)
print("patients: " + str(c) + ", minutes: " + str(c * 15))
if c > 12:
print("over limit!")
for x in l:
if x[2] == t and x[3] != "cancelled":
if x[4] == "":
print("SMS skipped: " + x[0])
else:
print("SMS to " + x[4] + ": see you at " + x[1])
proc(appointments, "2026-11-10")09:00 Rafi Ahmed (no phone)
09:15 Joseph Das (01700000004)
09:30 Ayesha Khan (01700000001)
patients: 3, minutes: 45
SMS to 01700000001: see you at 09:30
SMS skipped: Rafi Ahmed
SMS to 01700000004: see you at 09:15It probably took you a while. Nothing in it is wrong, but almost everything makes the reader work: proc, l, t, x, r, c and p say nothing; x[3] means "status" only if you remember the tuple order; 15 and 12 appear without explanation; the "no phone" check is written twice; and the function mixes finding, formatting and printing. Three habits fix most of this.
Names that say what things are
A good name answers "what is this?" without the reader looking elsewhere. Compare:
| Unclear | Clear | Why |
|---|---|---|
proc(l, t) | print_day(appointments, day) | A function name says what it does (a verb); arguments say what they hold. |
c | count or len(active) | Single letters are fine only for tiny, obvious loops. |
x[3] | a.status | A named field cannot be confused with its neighbour. |
data2, tmp | cancelled_today | Numbers and "tmp" hide the meaning. |
Use the words of the problem: if Nadia and Rina say "appointment" and "queue", the code should too. That is the same vocabulary you fixed in the ER diagram on the previous page.
Small functions with one job
A function should do one thing that you can describe in one short sentence without "and". "Find today's active appointments" is one job; "find, format, count, warn and print" is five. Small functions are easier to name, to read, to test and to reuse. This is the idea of high cohesion from Software Design Basics: From Requirements to Modules, applied inside a single file: everything in a function belongs to one purpose.
Small is not a number of lines. A rule of thumb: if you need to scroll, or you want to put a comment like "now do part 2" in the middle, the function is probably doing two jobs.
Clear control flow
Deep nesting (an if inside an if inside a for) forces the reader to keep every condition in their head. Two simple techniques flatten it:
- Combine conditions that belong together:
if date == day and status != "cancelled":instead of two nestedifs. - Return or continue early (often called a guard clause): handle the special case first and leave, so the main path is not indented.
if not a.phone: return "SMS skipped: ..."and then the normal case.
Comments and docstrings
The code already says what it does; a comment should add what the code cannot say: why it does it, a warning, or where a rule came from. A docstring is the string on the first line inside a function; Python keeps it and shows it in help(). Use it to say what the function does, what it expects and what it returns, in one or two sentences.
Example:
c = c + 1 # add 1 to c <- repeats the code: delete it
# slots are 10 minutes <- stale: the next line says 15
MINUTES_PER_PATIENT = 15
for a in active: # reminders keep booking order, as before
<- why: tells a reader not to "fix" it
def active_on(appointments, day):
"""Appointments on `day` that are not cancelled, in booking order."""The stale comment is the dangerous one. A comment that has not been updated after a change is worse than no comment, because the reader trusts it. When you change code, read the comments around it and update or delete them in the same change.
Practitioners disagree about how many comments are healthy. One view says good names and small functions make most comments unnecessary, so a comment is a sign the code could be clearer. Another says that reasons, decisions and links to requirements are lost if nobody writes them down. Both agree on the middle: first make the code as clear as you can, then comment on what is still not obvious, mainly the why.
Coding standards and style guides
A style guide is a written agreement on how code looks: indentation, line length, naming, blank lines, import order. For Python, the common one is PEP 8, the style guide in the Python Enhancement Proposals. Its reason is stated plainly: "code is read much more often than it is written". A few of its rules:
| Topic | PEP 8 |
|---|---|
| Indentation | "Use 4 spaces per indentation level." "Spaces are the preferred indentation method." |
| Line length | "Limit all lines to a maximum of 79 characters." Docstrings and comments wrap at 72. A team that agrees may go up to 99. |
| Names | Functions and variables in lowercase with underscores (print_day); classes in "CapWords" (Appointment); constants in capitals with underscores (MAX_PATIENTS_PER_DAY); modules with "short, all-lowercase names". |
| Layout | "Surround top-level function and class definitions with two blank lines." Imports on separate lines. |
PEP 8 also has a section called "A Foolish Consistency is the Hobgoblin of Little Minds". Its point: consistency within one project or module matters more than the guide itself. If ClinicQueue's code base does something one way, new code should match it, and the team decides together when to change the convention.
Formatters and linters
Nobody should spend review time on spaces and commas. Two kinds of tools take that work away:
- A formatter rewrites the layout of your code automatically (indentation, line breaks, quotes) so that everyone's code looks the same.
- A linter reads your code without running it and warns about likely problems: an unused variable, a name used before it is defined, an
exceptthat hides every error, a line that breaks the style guide.
The tool matters less than the habit: the team picks one formatter and one linter, writes the settings into the project, and runs them on every change, ideally automatically before the code reaches review. Then reviews can focus on logic and design.
Refactoring step by step
Refactoring means changing the structure of code without changing what it does. The rule that makes it safe: small steps, and check the behaviour after every step. If a check fails, you know the last small step broke it.
Step 0: record what it does now
Before touching proc, Farhan records its exact output for a known input. This is the safety net. (Proper automated tests do this job better; they come on Software Quality, Testing and QA.)
import contextlib
import io
def captured(func, *args):
"""Run func and return everything it printed, as one string."""
buffer = io.StringIO()
with contextlib.redirect_stdout(buffer):
func(*args)
return buffer.getvalue()
before = captured(proc, appointments, "2026-11-10")
print(len(before.splitlines()), "lines recorded")7 lines recordedStep 1: names and constants
Only the names change, the two magic numbers get names, and the nested ifs are combined. Unpacking each tuple into named variables removes the x[3] puzzles. The last line checks that the output is unchanged.
MINUTES_PER_PATIENT = 15
MAX_PATIENTS_PER_DAY = 12
def print_day(appointments, day):
queue = []
count = 0
for patient, time, date, status, phone in appointments:
if date == day and status != "cancelled":
shown_phone = phone if phone else "no phone"
queue.append(f"{time} {patient} ({shown_phone})")
count += 1
for line in sorted(queue):
print(line)
minutes = count * MINUTES_PER_PATIENT
print(f"patients: {count}, minutes: {minutes}")
if count > MAX_PATIENTS_PER_DAY:
print("over limit!")
for patient, time, date, status, phone in appointments:
if date == day and status != "cancelled":
if phone:
print(f"SMS to {phone}: see you at {time}")
else:
print(f"SMS skipped: {patient}")
print(captured(print_day, appointments, "2026-11-10") == before)TrueStep 2: named fields and one job per function
Now the structure changes. A small Appointment class with named fields replaces bare tuples, the filter is written once in active_on instead of twice, and each line of output has a function that builds it. print_day becomes a short list of steps that reads almost like the description of the job.
from typing import NamedTuple
class Appointment(NamedTuple):
patient: str
time: str # "HH:MM", clinic time zone
date: str # ISO date, "YYYY-MM-DD"
status: str
phone: str # "" when the patient gave no phone number
def active_on(appointments, day):
"""Appointments on `day` that are not cancelled, in booking order."""
return [a for a in appointments
if a.date == day and a.status != "cancelled"]
def queue_line(a):
return f"{a.time} {a.patient} ({a.phone or 'no phone'})"
def reminder_line(a):
if not a.phone:
return f"SMS skipped: {a.patient}"
return f"SMS to {a.phone}: see you at {a.time}"
def summary_line(count):
return f"patients: {count}, minutes: {count * MINUTES_PER_PATIENT}"
def print_day(appointments, day):
"""Print the front-desk queue for `day`, then the reminder SMS lines."""
active = active_on(appointments, day)
for line in sorted(queue_line(a) for a in active):
print(line)
print(summary_line(len(active)))
if len(active) > MAX_PATIENTS_PER_DAY:
print("over limit!")
for a in active: # reminders keep booking order, as before
print(reminder_line(a))
records = [Appointment(*row) for row in appointments]
after = captured(print_day, records, "2026-11-10")
print(after == before)
print(after, end="")True
09:00 Rafi Ahmed (no phone)
09:15 Joseph Das (01700000004)
09:30 Ayesha Khan (01700000001)
patients: 3, minutes: 45
SMS to 01700000001: see you at 09:30
SMS skipped: Rafi Ahmed
SMS to 01700000004: see you at 09:15Notice one odd detail that the refactoring kept on purpose: the queue is sorted by time, but the SMS lines stay in booking order. Maybe that is a bug, maybe Rina wants it. Refactoring does not decide; it keeps the behaviour. Changing behaviour is a separate, deliberate step, with its own check and its own commit, so that a reviewer can see each kind of change clearly.
Was it worth it?
The new version is longer. That is normal and fine: what matters is the cost of the next change. When Nadia changes slots to 20 minutes, there is one constant to edit. When the reminder wording changes (for the AI-drafted text, for example), there is one small function, reminder_line, to change and test. When a "no phone" rule changes, it changes in one place. Refactor when you are about to change code or when you have just made it work, not as a big separate project that stops feature work for weeks.
Errors, validation, magic numbers and duplication
Validate input at the boundary
Data from outside the program (a form, a file, another system) can be wrong in ways your code never expected. Check it once, where it enters, and turn it into clean objects; the rest of the code can then trust it. Two real problems hide in ClinicQueue's imported rows: a time written as "9:45" (which would sort after "10:00", because text is compared character by character) and a status written as "Cancelled" with a capital letter (which is not in the fixed list agreed in the ER model).
import datetime
VALID_STATUSES = {"booked", "cancelled", "arrived", "done"}
def parse_appointment(row):
"""Turn one raw row into an Appointment, or raise ValueError saying why."""
if len(row) != len(Appointment._fields):
raise ValueError(f"expected 5 fields, got {len(row)}: {row!r}")
a = Appointment(*row)
if a.status not in VALID_STATUSES:
raise ValueError(f"{a.patient}: unknown status {a.status!r}")
datetime.date.fromisoformat(a.date) # raises ValueError if bad
try:
datetime.time.fromisoformat(a.time)
except ValueError:
message = f"{a.patient}: time must be HH:MM, got {a.time!r}"
raise ValueError(message) from None
return a
def load(rows):
"""Keep the good rows and collect a message for each bad one."""
good, problems = [], []
for row in rows:
try:
good.append(parse_appointment(row))
except ValueError as error:
problems.append(str(error))
return good, problems
new_rows = appointments + [
("Nusrat Jahan", "9:45", "2026-11-10", "booked", "01700000006"),
("Tomas Gomes", "11:00", "2026-11-10", "Cancelled", ""),
]
good, problems = load(new_rows)
print(len(good), "good rows")
for message in problems:
print("problem:", message)5 good rows
problem: Nusrat Jahan: time must be HH:MM, got '9:45'
problem: Tomas Gomes: unknown status 'Cancelled'Handling errors honestly
- Say what is wrong, with the value. "Tomas Gomes: unknown status 'Cancelled'" lets Rina fix the row in a minute; "invalid input" does not.
- Choose: stop or collect. For saving a new booking, reject the bad request at once (fail fast). For showing the day's queue, it is better to show the good rows plus a clear list of problems than an empty screen. The choice depends on who suffers from each kind of failure.
- Never hide errors.
except: passturns a loud, fixable failure into silent wrong data. Catch only the errors you expect (hereValueError) and do something useful with them.
Magic numbers
A magic number is a literal value whose meaning is not written anywhere: the 15 and the 12 in proc. Readers must guess what it means, and when the rule changes someone must find every copy, including the 15 that is really "minutes" and not the 15 that happens to be something else. A named constant (MINUTES_PER_PATIENT = 15) gives the meaning and a single place to change it. Not every literal is magic: 0, 1 and an empty string are usually clear.
Duplication
The messy version checked "date matches and not cancelled" twice and "phone is empty" twice. Duplicated logic is a bug waiting to happen: one day someone adds "arrived patients get no SMS" to one copy and forgets the other. The rule of thumb DRY (don't repeat yourself) says each rule should live in one place. Like the other rules of thumb from the design page, it is not a law: two pieces of code that look the same today but stand for different rules may be better left separate, because they will change for different reasons.
Where this shows up at work
- Most of a developer's time on an existing product is spent reading code; clear names and small functions make every task faster.
- Teams write their style choices into the project and run a formatter and linter automatically, so reviews are about logic.
- "Leave the code a little cleaner than you found it": small refactorings are made alongside feature work, each in its own reviewed change.
- Error messages written for humans save support time: the front desk can fix bad data without calling a developer.
Common mistakes
- Refactoring and changing behaviour in one go. When the output changes, nobody knows whether it was intended. Fix: separate steps, each with a check; behaviour changes get their own commit.
- Refactoring without a safety net. Without a recorded output or tests, "it looks the same" is a guess. Fix: capture the current behaviour first.
- Comments that explain bad names.
c = 0 # number of patientsshould bepatient_count = 0. Fix: rename first, comment only what remains unclear. - Arguing about style in reviews. It wastes time and feels personal. Fix: agree a style guide once, let a formatter and linter enforce it.
- Swallowing errors to make a crash go away. The crash disappears and wrong data appears. Fix: catch specific errors and report them clearly.
Try it yourself
Code for exercise 1:
def chk(p):
# check phone has 10 digits
if len(p) == 11:
if p.isdigit():
return 1
return 0Code for exercise 3:
def m(l):
t = 0
for i in l:
if i[1] != "cancelled":
if i[2] == "child":
t = t + 10
else:
t = t + 15
return t- Easy: List every maintainability problem in
chk(exercise 1 code) and write a better version. - Medium: Suppose Farhan had skipped validation and the row with time "9:45" had reached the queue. Where would Nusrat Jahan appear in the sorted queue for 2026-11-10, and why? What would the front desk see?
- Hard: The function
m(exercise 3 code) computes the planned doctor minutes for a list of(patient, status, kind)visits. Refactor it: clear names, no magic numbers, a docstring, and validation ofkind. Then show that your version gives the same result asmon a sample, and name one input where the two versions behave differently.
Answers
- Problems: the names
chkandpsay nothing; the comment is stale (it says 10 digits, the code checks 11); 11 is a magic number; nestedifs where one condition would do; it returns 1 and 0 instead ofTrueandFalse. A better version:PHONE_DIGITS = 11, thendef is_valid_phone(phone): return len(phone) == PHONE_DIGITS and phone.isdigit(), with a docstring such as "True if phone is exactly PHONE_DIGITS digits, nothing else." A good answer finds at least the names, the stale comment and the magic number, and its new version returns a boolean. - Text is compared character by character. "9:45 Nusrat Jahan ..." starts with "9", and every other line starts with "0" ("09:00", "09:15", "09:30"), so her line sorts after all of them: she appears last, as if she came after the 09:30 patient, although her slot is at 09:45 and the list looks plausible. With a later patient at "10:00" she would even appear after that one, since "1" comes before "9". The front desk would call patients in the wrong order without any error message. That is why validating the format at the boundary matters: the bug is quiet, not loud.
- Model answer below. A good answer has: a descriptive function name and loop variables; the 10 and 15 in one named mapping or two constants; a one-line docstring; a clear error for an unknown kind; a check on sample data that both versions agree. The difference: the old
mcounts any kind that is not exactly "child" as 15 minutes, so a typo such as "Child" or "baby" silently becomes an adult visit, while the new version raisesValueError. That is a behaviour change, so a good answer says it should be agreed and made as its own step, not hidden inside the refactoring.
Model answer for exercise 3:
def m(l):
t = 0
for i in l:
if i[1] != "cancelled":
if i[2] == "child":
t = t + 10
else:
t = t + 15
return t
VISIT_MINUTES = {"child": 10, "adult": 15}
def planned_minutes(visits):
"""Total doctor minutes for the visits that are not cancelled."""
total = 0
for patient, status, kind in visits:
if status == "cancelled":
continue
if kind not in VISIT_MINUTES:
raise ValueError(f"{patient}: unknown visit kind {kind!r}")
total += VISIT_MINUTES[kind]
return total
sample = [
("Rafi Ahmed", "booked", "child"),
("Ayesha Khan", "booked", "adult"),
("Mim Akter", "cancelled", "child"),
("Joseph Das", "arrived", "adult"),
]
print(m(sample), planned_minutes(sample), m(sample) == planned_minutes(sample))40 40 TrueSummary
- Maintainable code can be read and changed safely by someone else; clear names, small one-job functions and flat control flow do most of the work.
- Comments explain why, docstrings say what a function does; update or delete comments when the code changes.
- A style guide such as PEP 8 ("code is read much more often than it is written") plus an agreed formatter and linter keeps code consistent without review arguments.
- Refactoring changes structure, not behaviour: record the behaviour first, take small steps, check after each one, and change behaviour separately.
- Validate input where it enters, report errors clearly and never hide them; replace magic numbers with named constants and keep each rule in one place.
Next: Code Review, Version Control and Team Workflow: how a team checks each other's code, uses branches and pull requests, and keeps the main code always ready to release.

