Skip to content

Module 20 · Building Real Python Applications — topic 12 of 13

Improving code quality

Making working code better: refactoring safely with tests, simplifying loops and string building, replacing branch chains with data, finding long functions automatically, and using linters, type checkers and reviews.

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

Learning objectives

  • Refactor code safely behind tests
  • Replace complex branching with data-driven code
  • Use tools to find quality problems

Definition

Improving code quality means changing code to make it clearer, simpler and easier to maintain without changing what it does (refactoring), supported by tests, automated tools and code review.

Introduction

The expense tracker works. Now is the time to make it pleasant to change — before the next feature makes the messy parts harder to fix.

Why it matters

Quality improvements pay off with every future change: fewer bugs, faster features and code you're proud to show.

Detailed explanation

Refactoring changes structure, not behaviour. Always have tests (or at least comparison checks) that prove the result stays the same.

Work in small steps: rename, extract a function, simplify a condition — then run the tests.

Use Python idioms: iterate directly instead of with indexes, join strings instead of repeated +, use comprehensions for simple transformations.

Replace long if/elif chains that differ only in numbers with a data table (dictionary), so new cases are data, not code.

Measure: very long functions, deep nesting and duplicated blocks are signs that code needs attention. The ast module or linters can find them.

Run linters (ruff), formatters (ruff format, black) and type checkers (mypy) regularly; they find problems humans miss.

Ask for code review: a second reader spots unclear names and missing cases.

Stop when the code is clear; perfect is the enemy of finished.

Syntax

Python
RATES = {"local": (40, 10), "national": (80, 20)}
def shipping_cost(zone, weight):
base, per_kg = RATES[zone]
return base + max(weight - 1, 0) * per_kg
  • Same behaviour, better structure.
  • Small steps with tests.
  • Data instead of branch chains.

Code examples

A simpler version with the same result

Python
def report_v1(items):
s = ""
for i in range(len(items)):
s = s + items[i][0] + ": " + str(items[i][1]) + "\n"
return s
def report_v2(items):
return "".join(f"{name}: {amount}\n" for name, amount in items)
items = [("food", 370), ("travel", 40)]
print(report_v1(items) == report_v2(items))
print(report_v2(items), end="")
Output
True
food: 370
travel: 40

Finding long functions automatically

Python
import ast
source = "def short():\n return 1\n\ndef long_one(x):\n" + "".join(f" x += {i}\n" for i in range(30)) + " return x\n"
tree = ast.parse(source)
for node in tree.body:
if isinstance(node, ast.FunctionDef):
length = node.end_lineno - node.lineno + 1
print(node.name, length, "consider splitting" if length > 20 else "ok")
Output
short 2 ok
long_one 32 consider splitting

More examples

Replacing a branch chain with data

Python
def shipping_cost_v1(zone, weight):
if zone == "local":
if weight <= 1:
return 40
else:
return 40 + (weight - 1) * 10
elif zone == "national":
if weight <= 1:
return 80
else:
return 80 + (weight - 1) * 20
elif zone == "international":
if weight <= 1:
return 500
else:
return 500 + (weight - 1) * 150
else:
raise ValueError("unknown zone")
RATES = {"local": (40, 10), "national": (80, 20), "international": (500, 150)}
def shipping_cost(zone: str, weight: float) -> float:
"""Base price for the first kilogram plus a per-kilogram rate after that."""
try:
base, per_kg = RATES[zone]
except KeyError:
raise ValueError(f"unknown zone: {zone}") from None
return base + max(weight - 1, 0) * per_kg
cases = [(z, w) for z in RATES for w in (0.5, 1, 2.5, 10)]
print(all(shipping_cost(z, w) == shipping_cost_v1(z, w) for z, w in cases), len(cases))
print(shipping_cost("national", 2.5))
Output
True 12
110.0

Step-by-step explanation

  • The old version repeats the same formula three times with different numbers.
  • The new version keeps the numbers in a table and the formula in one place.
  • Comparing both on 12 cases shows the refactor preserved behaviour before the old version is deleted.

Expected output

Running “Replacing a branch chain with data” prints exactly:

TextOutput
True 12
110.0

Practical applications

  • Tidying a project before submitting it for review or a portfolio.
  • Teams reserving time each sprint to pay down technical debt.

Best practices

  • Refactor in small, tested steps.
  • Prefer data tables to repeated branches.
  • Automate quality checks.

Common mistakes

Refactoring without a safety net

Avoid

# rewrite the module and hope

Prefer

# write comparison tests, refactor in small steps, run them each time

Without tests, 'cleaner' code may silently behave differently.

Important notes

  • Tools such as radon measure cyclomatic complexity, a count of independent paths through a function.

Key takeaways

  • Refactoring improves structure without changing behaviour.
  • Tests and comparisons prove behaviour is preserved.
  • Linters, metrics and reviews guide improvements.

Try it yourself

  1. 1
    Pick the longest function in one of your projects and split it into smaller ones, keeping a test passing.
  2. 2
    Replace a grading if/elif chain with a data-driven version and prove both agree.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions cover the “Building Real Python Applications” module. Answers and explanations are revealed after you submit.

  • AdvancedWhat does MVP stand for when planning an application?
  • AdvancedWhere should input validation ideally happen?
  • AdvancedWhat is printed?
Practise this module