Layered architecture
Overview
Layered architecture is a way to organize your code into separate levels, like a multi-story building. Each layer has a specific job and only talks to the layer directly below it. ```python # Layer 1: Presentation (handles user requests) def handle_user_request(user_id): return get_user_logic(user_id) # Layer 2: Business Logic (makes decisions) def get_user_logic(user_id): if user_id < 0: return 'Invalid' return fetch_from_db(user_id) # Layer 3: Data (talks to database) def fetch_from_db(user_id): return f'User {user_id} data' ``` The rule: **A layer can only call functions in the layer below it.** The presentation layer cannot talk directly to the database. Think of it like a restaurant: the waiter (presentation) takes your order to the chef (logic), and the chef gets ingredients from the pantry (data). The waiter never goes to the pantry.
It keeps code from becoming a tangled mess. If you change your database, you only rewrite the data layer, not the whole app.
Where used: Backend web applications, Enterprise software
Why learn this
- Most real-world companies use this to keep their code organized.
- It makes finding and fixing bugs much easier because every job has a specific place.
Code walkthrough
def api(req):
return logic(req)
def logic(req):
return data(req) + ' updated'
def data(req):
return 'record'
print(api('get'))
Focus: return logic(req)
Common mistakes
- Skipping layers: Making the presentation layer call the database directly. This defeats the purpose and makes the code hard to test.
- Mixing logic: Putting complex business rules (like calculating discounts) inside the database layer or the presentation layer.
Recall questions
- Explain layered architecture in your own words, as if to a classmate.
- Can the presentation layer talk directly to the data layer?
- Why is this better than putting all the code in one place?
Understanding checks
What does this print?
processed data
The request goes from the UI, to the logic, to the DB, and then the DB returns 'data' which the logic layer modifies before giving it to the UI.
What architectural rule does this code break?
The presentation layer (`web_route`) calls the data layer (`db_query`) directly.
In a layered architecture, the top layer must go through the middle business logic layer, not skip it to talk to the DB directly.
Practice tasks
Fix the skipped layer
Modify this code so that the `handle_click` function calls `process_click` instead of talking to the database directly.
Continue learning
Previous: Package structure and __init__.py