Separation of concerns

On this page 7

Separation of concerns is the design principle of dividing a program into distinct parts so that each part addresses one well-defined concern, such as data storage, business rules or presentation, and knows as little as possible about the others. In programming architecture, it is the foundational idea behind layers, modules, components and most named patterns, because it keeps each kind of change confined to the code responsible for it.

The phrase is usually credited to Edsger W. Dijkstra, who used it in the 1970s to describe focusing on one aspect of a problem at a time. Applied to software structure, the principle aims for high cohesion within a unit and low coupling between units, which together make systems easier to understand, test and evolve.

What counts as a concern

A concern is any distinct aspect of a system that can change for its own reasons, independently of other aspects. The practical test is simple: if two pieces of logic change at different times, for different stakeholders, they represent different concerns and belong in different places.

Concerns appear at many scales, from a single function up to an entire service. The table below lists frequent categories and the boundary that typically separates them.

ConcernTypical responsibilityCommon boundary
PresentationRendering output and handling user inputView or UI layer
Business logicRules, calculations and workflows of the domainDomain layer or service
Data accessReading and writing persistent storageRepository or data mapper
IntegrationCalling external APIs and message brokersAdapter or gateway
ConfigurationEnvironment-specific settings and secretsConfiguration files or service
Cross-cuttingLogging, security, caching, transactionsMiddleware, decorators or aspects
Common concerns and their usual boundaries

How separation of concerns is achieved

Separation is achieved by drawing explicit boundaries and controlling what crosses them. The main mechanism is the interface or contract: one part depends on an abstract description of what another part does, not on how it does it.

  • Modularization groups related code into modules, packages or namespaces with limited public surfaces.
  • Layering arranges concerns so that each layer depends only on the layer beneath it or on abstractions.
  • Encapsulation hides internal state and exposes only the operations other parts need.
  • Dependency inversion lets high-level policy define interfaces that low-level details implement.
  • Aspect-oriented techniques and middleware isolate cross-cutting concerns that would otherwise be scattered.

Tools such as dependency injection and inversion of control containers support the principle by assembling separated parts at runtime, so that no component needs to construct its own collaborators. They are means of separation, not the principle itself.

Boundaries are only as strong as their enforcement. Many teams add automated architecture tests or module dependency rules that fail the build when, for example, a domain package imports a web framework. Without such checks, deadline pressure gradually lets forbidden dependencies creep across layers until the separation exists only in diagrams.

Separation of concerns is the general principle, and many architecture terms are specific applications of it. Seeing that relationship clarifies why these patterns resemble one another.

ConceptScopeHow it separates concerns
Single responsibility principleClass or moduleOne reason to change per unit
MVCUser interfaceSplits model, view and controller
MVVMUser interfaceMoves view state into a view model
Hexagonal architectureApplicationIsolates domain core behind ports and adapters
Clean architectureApplicationConcentric layers with inward dependencies
Domain-driven designSystemBounded contexts separate business domains
MicroservicesDeploymentSeparates concerns into independently deployed services
How related concepts apply the principle

The single responsibility principle within the SOLID principles is often treated as a synonym, but it is narrower: it applies to individual classes, while separation of concerns applies to any level of decomposition, including files, processes and teams.

Benefits and the cost of separation

Well-separated code delivers measurable engineering benefits, but every boundary also has a cost in indirection and coordination. The aim is a balance, not maximum fragmentation.

AspectBenefitAssociated cost
ChangeabilityChanges stay local to one unitMore files and interfaces to navigate
TestabilityUnits can be tested with test doublesMocks may drift from real behavior
ReusabilityIsolated parts can serve other contextsGeneric designs can be overengineered
Team autonomyGroups own separate parts in parallelContracts require coordination
ComprehensionEach unit is small enough to understandFollowing one request spans many units
Benefits and corresponding costs

A useful heuristic is to separate along lines of actual or strongly expected change. Splitting code for hypothetical future needs often yields abstractions that nobody uses, a pattern summarized by the guideline known as YAGNI, short for you are not going to need it.

Common mistakes when applying the principle

Violations tend to show recognizable symptoms in a codebase. Diagnosing them early prevents the gradual erosion of structure often called architectural drift.

SymptomLikely causeTypical fix
SQL queries inside UI handlersData access mixed with presentationIntroduce a repository or service layer
One change touches many modulesConcern scattered across unitsConsolidate logic in one module
Tests need a database to check a ruleBusiness logic coupled to storageExtract pure domain functions
Layers pass data through unchangedSeparation without real responsibilityRemove the empty layer
Logging code repeated everywhereCross-cutting concern not isolatedUse middleware or decorators
Symptoms of poor separation and their fixes

The opposite mistake, over-separation, is equally damaging. Splitting a small program into many thin layers produces lasagna code, where understanding a single feature requires reading a stack of trivial delegating classes.

The short version

Think of a restaurant. The kitchen cooks, the waiters serve, and the cashier handles payments. Each group does its own job and does not need to know the details of the others. If the menu changes, the cashier keeps working as before.

Separation of concerns applies the same idea to software. Each part of a program handles one job, so a change in one area does not break everything else, and people can work on different parts at the same time.

Where it makes a difference

A development team maintains an online booking system whose page handlers contain pricing rules, database queries and HTML generation in the same functions. When the business asks for a new mobile app that uses the same prices, the team discovers that the pricing logic cannot be reused without copying hundreds of lines tied to web templates.

Over three sprints the team moves pricing into a separate domain module with no dependency on storage or presentation, places all queries behind a repository interface, and keeps the web handlers thin. The mobile backend then calls the same pricing module directly. Unit tests for the pricing rules run in under two seconds instead of needing a test database, and a later change to discount rules is made in one module instead of eleven files.