Modular design and separation of concerns
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
- It is the foundation of writing code that other people can actually read and use.
- It prevents the 'spaghetti code' problem where changing one thing breaks everything.
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
- God functions: Writing a massive 500-line function that does ten different things. Break it down into smaller helper functions.
- False reusability: Trying to make a function so generic that it takes 15 arguments to handle every possible situation. Keep it simple.
Recall questions
- Explain separation of concerns in your own words, as if to a classmate.
- How can you tell if a function is doing too much?
- Why is a modular design better than putting everything in one file?
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