Separation of Concerns
Separation of Concerns (SoC) is the principle that each module, class, or function should have one reason to change — it should be responsible for one coherent piece of the system's purpose, and everything else should be someone else's problem. It's the principle behind layered architecture, MVC, module boundaries, and single-responsibility design. When concerns are well-separated, changes are local (you know exactly what to edit), tests are simple (you test one thing at a time), and code is reusable (a service that knows nothing about HTTP can be called from a REST route, a GraphQL resolver, or a CLI script). This page makes the principle concrete with Node examples.
One reason to change
// ❌ Mixed concerns — this function has at least FOUR reasons to change:
app.post('/users', async (req, res) => {
if (!req.body.email?.includes('@')) return res.status(400).json({ error: 'bad email' })
const hash = await bcrypt.hash(req.body.password, 10)
const [user] = await db.query('INSERT INTO users(email,pass) VALUES($1,$2) RETURNING *',
[req.body.email, hash])
await sendEmail(req.body.email, 'Welcome!')
logger.info('user created', user.id)
res.status(201).json({ id: user.id })
})
// Reasons to change: (1) API contract, (2) validation rules, (3) DB schema,
// (4) email template, (5) log format — one function owns all of them.Practical separations that pay off
Concern | Its own module | Why it helps |
|---|---|---|
Input validation |
| Rules change independently of business logic; reusable across REST + GraphQL |
Business logic |
| Testable without HTTP or a database; reusable from any caller |
Data access |
| Swap ORM/DB without touching services; mock in tests |
Error types |
| Consistent error codes; can be mapped to HTTP status in one place |
Config |
| One validated source of truth; no |
Logging | injected logger | Swap implementation; silence in tests without mocking |
Cross-cutting concerns — where SoC gets tricky
// Cross-cutting concerns cut across EVERY layer: logging, auth, timing, tracing.
// They belong in MIDDLEWARE or DECORATORS, not scattered in every function.
// ❌ Logging sprinkled everywhere — couples every function to the log format:
async function createUser(dto) {
console.log('creating user', dto.email)
// ...
console.log('user created', user.id)
}
// ✅ Logging as cross-cutting infrastructure — applied at the layer boundary:
// HTTP middleware logs every request automatically (morgan, pino-http)
// Service functions receive a logger via injection, or a request-scoped store