Separation of Concerns
Separation of concerns means splitting a program into parts so that each part deals with one concern, such as showing data, applying business rules or talking to a database. A concern is a distinct thing the software has to care about.
The idea
Ask of every function, class or module: what is the one reason this would need to change? If the answer is “the page layout, the tax rules and the SQL schema”, it has too many concerns.
Typical concerns in an application:
- Presentation covers what the user sees and how input is collected.
- Business logic holds the rules of the domain (a discount applies when…).
- Data access reads and writes storage.
- Cross-cutting concerns cover logging, authentication, error handling and configuration.
An example
A function handleOrder(request) that parses the HTTP request, checks stock with an inline SQL query, calculates the price, writes the order and builds the HTML response does five jobs. Split it up:
handler parse request, call the service, build the response
orderService validate order, calculate price, apply rules
orderStore save and load orders (the only code that knows SQL)
Now the price rules can be unit tested without a web server or database, the database can be swapped without touching the rules, and the response format can change without touching the price logic.
Signs of mixed concerns
- Business rules written inside UI event handlers or SQL strings.
- A “utils” file that grows without limit.
- Tests that need a database or network to check simple logic.
- Changing one feature means editing many unrelated files.
Habits for splitting code
- Keep functions small and named after what they do (see Clean Code and Naming).
- Let the outer parts depend on the inner ones: the rules should not know about HTTP.
- Do not over-split. A tiny script does not need five layers. Separate when the parts change for different reasons.
Separation of concerns is the principle behind Layered Architecture, and the ideas in Modularity, Coupling, and Cohesion tell you how well you have done it. It also makes unit testing much easier.
Try it
Pick a function in a project you work on that does more than one job. List the concerns it mixes, then extract one of them into its own function or module without changing behaviour. Check whether the extracted part is easier to test.
Common mistakes
- Writing business rules inside UI event handlers or SQL strings.
- Letting a utils file grow without limit.
- Over-splitting a tiny script into many layers.
Check yourself
- What question reveals mixed concerns in a function?
- Why is price logic easier to test once it is separate from HTTP and SQL?
- Name three signs of mixed concerns.