Modular design and separation of concerns

RoadmapsPython

Overview

Separation of concerns is the idea that every piece of your code should do exactly one thing. Modular design means breaking a large program into small, independent parts (modules) based on those concerns. ```python # Bad: Doing everything in one function def process_order(): # calculate tax, check inventory, send email... pass # Good: Separated concerns def calculate_tax(amount): return amount * 0.1 def check_inventory(item): return True ``` The rule: **If a function or file has the word 'and' in its description, it is doing too much.** Think of it like a hospital: a doctor diagnoses you, a nurse draws blood, and a pharmacist gives medicine. If one person did all three, the hospital would collapse.

It makes your code easier to read, test, and reuse. If you need to calculate tax somewhere else, you can just reuse the small function.

Where used: Writing clean code, System design

Why learn this

Code walkthrough

def calc(price):
    return price * 1.1

def print_receipt(amount):
    print(f'Total: {amount}')

total = calc(100)
print_receipt(total)

Focus: total = calc(100)

Common mistakes

Recall questions

Understanding checks

What is wrong with this function's design?

It is doing two things: checking an age rule and talking to a database.

A function should only do one thing. Here, the validation (age check) and the data access (db check) are mixed.

If you have an `email_sender` module and a `payment_processor` module, should the email module know how payments are calculated?

No.

Concerns must be separated. The email module should only know how to send text, and the payment module should calculate the payment.

Practice tasks

Split the function

Modify this code to split the `process_student` function into two smaller functions: `get_grade` and `print_report`.

Continue learning

Previous: Defining functions and return values

Next: Layered architecture

Return to Python Roadmap