Skip to content

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

Breaking problems into components

Decomposing an application into components with single responsibilities: input parsing, business logic, storage and output; connecting them through simple data; testing each separately; and replacing one component without touching others.

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

Learning objectives

  • Decompose an application into components
  • Connect components through simple data
  • Test and replace components independently

Definition

Breaking a problem into components means dividing an application into smaller parts, each responsible for one job, that communicate through clear inputs and outputs. Components can be functions, classes or modules.

Introduction

An expense report needs reading lines, turning them into numbers, totalling by category and formatting a report. Four small jobs are easier than one big one.

Why it matters

Components can be understood, tested and improved one at a time, and teams can work on different components in parallel.

Detailed explanation

Start from the flow of data: input → parse → process → store → output. Each arrow is a natural boundary between components.

Give each component one responsibility. parse_line turns text into values; total_by_category does arithmetic; format_report produces text.

Connect components with simple data structures (tuples, dicts, dataclasses) rather than shared global state.

A clear interface — the inputs a component takes and the output it returns — lets you change its internals freely.

Test each component with its own small inputs; when the full program misbehaves, component tests show which part is wrong.

Replace a component (a table instead of a list report, a database instead of a file) by providing the same interface.

Decompose recursively: if a component is still large, split it again.

Avoid over-splitting: a component should be meaningful on its own, not a one-line wrapper.

Syntax

Text
lines → parse_line → (amount, category) → total_by_category → {category: total} → format_report → text
  • Follow the data flow.
  • One job per component.
  • Simple data between components.

Code examples

A decomposition tree

Text
Expense tracker
├── Input: read commands and arguments
├── Parsing and validation: amounts, categories, dates
├── Logic: add expense, totals, budgets
├── Storage: save and load expenses
└── Output: lists, reports, messages

Components as functions

Python
def parse_line(line):
amount, category = line.split(",")
return float(amount), category.strip()
def total_by_category(items):
totals = {}
for amount, category in items:
totals[category] = totals.get(category, 0) + amount
return totals
def format_report(totals):
return "\n".join(f"{c}: {t:.2f}" for c, t in sorted(totals.items()))
lines = ["250, food", "40, travel", "120, food"]
print(format_report(total_by_category(parse_line(line) for line in lines)))
Output
food: 370.00
travel: 40.00

More examples

Testing and replacing components

Python
def parse_line(line):
amount, category = line.split(",")
return float(amount), category.strip()
def total_by_category(items):
totals = {}
for amount, category in items:
totals[category] = totals.get(category, 0) + amount
return totals
def format_report(totals):
return "\n".join(f"{c}: {t:.2f}" for c, t in sorted(totals.items()))
assert parse_line("99.5, books") == (99.5, "books")
assert total_by_category([(10, "a"), (5, "a"), (1, "b")]) == {"a": 15, "b": 1}
assert format_report({"b": 1, "a": 2.5}) == "a: 2.50\nb: 1.00"
print("all components tested independently")
def format_table(totals):
width = max(len(c) for c in totals)
return "\n".join(f"{c:<{width}} | {t:>8.2f}" for c, t in sorted(totals.items()))
lines = ["250, food", "40, travel", "120, food"]
print(format_table(total_by_category(parse_line(line) for line in lines)))
Output
all components tested independently
food   |   370.00
travel |    40.00

Step-by-step explanation

  • Each assertion tests one component with tiny, hand-checked data.
  • format_table is a drop-in replacement for format_report: same input, different output.
  • Parsing and totalling didn't change at all when the output format did.

Expected output

Running “Testing and replacing components” prints exactly:

TextOutput
all components tested independently
food | 370.00
travel | 40.00

Practical applications

  • Web apps split into routes, services and database layers.
  • Data pipelines with extract, transform and load steps.

Best practices

  • Design around data flow.
  • Keep component interfaces small.
  • Test components before the whole.

Common mistakes

Components that share globals

Avoid

TOTALS = {}
def parse(line):
TOTALS[...] += ... # parsing also totals

Prefer

def parse(line): return amount, category
def total(items): ...

Hidden coupling makes components impossible to test or replace separately.

Important notes

  • The next lessons turn these components into a structured program with functions, classes and storage.

Key takeaways

  • Split applications along the data flow.
  • Each component has one job and a clear interface.
  • Components are tested and replaced independently.

Try it yourself

  1. 1
    Decompose a quiz application into components and write one function per component.
  2. 2
    Replace format_report with a CSV formatter without changing the other components.

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