Separation of Concerns
Divide your system into distinct sections, each addressing a separate concern.
Separation of Concerns (SoC) is the principle that a system should be divided into distinct sections, each addressing a separate concern. It’s the foundation of maintainable software.
Why It Matters
- Change isolation: A change in one concern shouldn’t ripple across the system.
- Testability: Each concern can be tested independently.
- Comprehension: Developers can understand one concern without understanding everything.
In Practice
Horizontal Separation (Layers)
┌──────────────────────┐
│ Presentation │ ← UI, HTTP handlers, CLI
├──────────────────────┤
│ Business Logic │ ← Domain rules, workflows
├──────────────────────┤
│ Data Access │ ← Database, external APIs
└──────────────────────┘
Vertical Separation (Bounded Contexts)
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Orders │ │ Billing │ │ Shipping│
│ ┌───┐ │ │ ┌───┐ │ │ ┌───┐ │
│ │UI │ │ │ │UI │ │ │ │UI │ │
│ ├───┤ │ │ ├───┤ │ │ ├───┤ │
│ │BL │ │ │ │BL │ │ │ │BL │ │
│ ├───┤ │ │ ├───┤ │ │ ├───┤ │
│ │DA │ │ │ │DA │ │ │ │DA │ │
│ └───┘ │ │ └───┘ │ │ └───┘ │
└─────────┘ └─────────┘ └─────────┘
Anti-Patterns
- God object: One class/module does everything.
- Shotgun surgery: A single change requires edits in many places.
- Leaky abstraction: Business logic bleeds into the data layer or vice versa.
Rules of Thumb
- If a class has more than one reason to change, split it.
- If a function does I/O and computation, separate them.
- If a module imports from every other module, it’s a concern magnet — refactor.
Next: Layered Architecture