Skip to content

Module 19 · Debugging, Testing and Best Practices — topic 15 of 15

Maintainable programs

Writing code that stays easy to change: avoiding duplication (DRY), configuration over hard-coding, small interfaces, extending without editing (open/closed), tests as a safety net, version control and refactoring habits.

Beginner 10 min read·Lesson 293 of 306 in Python Programming

Learning objectives

  • Remove duplication and hard-coded values
  • Design code that can be extended without editing existing parts
  • Use tests, version control and refactoring to keep code healthy

Definition

A maintainable program is one that can be understood, corrected and extended with reasonable effort over time. Maintainability comes from clear structure, little duplication, good tests and documentation, and designs that allow change.

Introduction

Most of a program's life is spent being changed: new features, bug fixes, new requirements. Maintainable code makes each change small and safe.

Why it matters

Unmaintainable code slows every future change and breeds bugs. Good habits early save enormous effort later.

Detailed explanation

Don't Repeat Yourself (DRY): when the same logic appears twice, move it into a function, so a fix happens in one place.

Replace hard-coded values with configuration (constants, settings files, environment variables) so behaviour changes without code changes.

Give each function and class a single responsibility; small, focused units are easier to understand and replace.

Design for extension: new features should be addable by writing new code (a new exporter, a new payment class) rather than editing existing, tested code. Registries and polymorphism make this possible.

Tests are the safety net that makes change possible; without them, every refactor is a risk.

Refactor continuously in small steps: rename, extract functions, simplify conditions — running tests after each step.

Use version control (git) with small, well-described commits, so changes can be reviewed and undone.

Technical debt — shortcuts taken to ship quickly — must be repaid; leave code a little cleaner than you found it.

Syntax

Python
EXPORTERS = {}
def exporter(name):
def register(fn):
EXPORTERS[name] = fn
return fn
return register
@exporter("csv")
def to_csv(rows): ...
  • Remove duplication.
  • Configure, don't hard-code.
  • Extend by adding code, not editing it.

Code examples

One function instead of repeated code

Python
def line(name, price, qty):
return f"{name:<6}{qty:>3} x {price:>4} = {qty * price:>5}"
print(line("pen", 20, 3))
print(line("book", 250, 2))
Output
pen     3 x   20 =    60
book    2 x  250 =   500

Configuration instead of hard-coding

Python
CONFIG = {"currency": "₹", "tax_rate": 0.18}
def format_price(amount, config=CONFIG):
return f"{config['currency']}{amount * (1 + config['tax_rate']):,.2f}"
print(format_price(1000), format_price(1000, {"currency": "$", "tax_rate": 0.0}))
Output
₹1,180.00 $1,000.00

More examples

Extending without editing

Python
import json
EXPORTERS = {}
def exporter(name):
def register(fn):
EXPORTERS[name] = fn
return fn
return register
@exporter("csv")
def to_csv(rows):
return "\n".join(",".join(map(str, r)) for r in rows)
@exporter("text")
def to_text(rows):
return "\n".join(" | ".join(map(str, r)) for r in rows)
def export(rows, fmt):
if fmt not in EXPORTERS:
raise ValueError(f"unknown format {fmt!r}; available: {', '.join(sorted(EXPORTERS))}")
return EXPORTERS[fmt](rows)
rows = [("pen", 20), ("book", 250)]
print(export(rows, "csv"))
print(export(rows, "text"))
@exporter("json") # a new feature: no existing code changed
def to_json(rows):
return json.dumps([{"item": i, "price": p} for i, p in rows])
print(export(rows, "json"))
try:
export(rows, "pdf")
except ValueError as e:
print(e)
Output
pen,20
book,250
pen | 20
book | 250
[{"item": "pen", "price": 20}, {"item": "book", "price": 250}]
unknown format 'pdf'; available: csv, json, text

Step-by-step explanation

  • Each exporter registers itself in a dictionary through a decorator.
  • export only looks formats up in the registry, so it never needs editing when formats are added.
  • The error message lists available formats automatically, so it stays correct as the registry grows.

Expected output

Running “Extending without editing” prints exactly:

TextOutput
pen,20
book,250
pen | 20
book | 250
[{"item": "pen", "price": 20}, {"item": "book", "price": 250}]
unknown format 'pdf'; available: csv, json, text

Practical applications

  • Plugin systems in editors and frameworks.
  • Long-lived business applications maintained by changing teams.

Best practices

  • Keep it DRY and configurable.
  • Design for extension with registries and polymorphism.
  • Refactor in small, tested steps under version control.

Common mistakes

Copy-paste programming

Avoid

# the same 15-line validation pasted in four places

Prefer

def validate_order(order): ... # called from all four

A bug fixed in one copy remains in the others.

Big-bang rewrites

Avoid

# rewrite the whole module at once, then test

Prefer

# refactor in small steps with tests after each

Small steps keep the program working and make mistakes easy to find.

Important notes

  • This completes the Debugging, Testing and Best Practices module; the final module brings everything together in real applications.

Key takeaways

  • Maintainable code is easy to understand and change.
  • Remove duplication and hard-coded values.
  • Tests, small refactors and version control keep it healthy.

Try it yourself

  1. 1
    Find duplicated code in one of your programs and extract it into a function.
  2. 2
    Add a markdown exporter to the registry example without changing export().

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Debugging, Testing and Best Practices” module. Answers and explanations are revealed after you submit.

  • AdvancedWhy shouldn't assert be used to validate user input?
  • AdvancedWhat is printed?
  • AdvancedWhere should you usually start reading a Python traceback?
Practise this module