Lesson 268 of 296
DRY vs over-abstraction, composition and separation of concerns
What you will learn
- DRY and what it really means
- The cost of the wrong abstraction
- WET, AHA and the rule of three
- Composition over inheritance
- Separation of concerns and layered architecture
- KISS and YAGNI
On this page
DRY: Don't Repeat Yourself
DRY says every piece of knowledge should have one authoritative place in the system. If the VAT rate or a validation rule is copied into five files, a change will be missed in one of them.
The key word is knowledge, not text. Two pieces of code that look the same but represent different business rules that will change for different reasons are not duplication.
The wrong abstraction
A common mistake: merging similar-looking code into one shared function too early. Then requirements diverge, and the shared function grows parameters and if branches for each caller:
function formatAmount(value, isInvoice, isReport, showSymbol, legacyMode, roundUp) { ... }Now every caller is coupled to every other, and nobody dares to change it. Sandi Metz's well-known advice: "duplication is far cheaper than the wrong abstraction." If an abstraction has turned out wrong, it is fine to inline it back into the callers and start again.
Rules of thumb:
- Rule of three: tolerate a second copy; abstract when the third appears and the pattern is clear.
- AHA ("avoid hasty abstractions"): wait until you understand what really varies.
- Prefer abstractions with a clear name in the business language (
calculateVat), not generic utilities with flags.
Composition over inheritance
Inheritance (class Manager extends Employee) creates tight coupling: subclasses depend on the parent's internals, deep hierarchies become hard to change, and many real things do not fit one tree (is a "flying fish" a fish or a bird?).
Composition builds behaviour by combining smaller objects or functions:
type Logger = { log(message: string): void };
type Clock = { now(): Date };
const consoleLogger: Logger = { log: (m) => console.log(m) };
const systemClock: Clock = { now: () => new Date() };
export function createReminderService(deps: { logger: Logger; clock: Clock }) {
return {
isOverdue(dueAt: Date): boolean {
const overdue = deps.clock.now() > dueAt;
if (overdue) deps.logger.log(`Overdue since ${dueAt.toISOString()}`);
return overdue;
}
};
}
export const reminders = createReminderService({ logger: consoleLogger, clock: systemClock });The service has a logger and a clock; it does not inherit from a "LoggingClockService" base class. In tests, pass a fake clock. React itself is built on composition (Lesson 165), and modern TypeScript favours functions, small interfaces and composition. Inheritance is still fine for genuine "is-a" relationships with stable shared behaviour (for example custom Error classes, Lesson 82), and frameworks sometimes require it (error boundaries, Lesson 173).
Separation of concerns
Each part of the code handles one concern: presentation, business rules, data access, external integrations. A typical back-end layering:
| Layer | Responsibility | Knows about |
|---|---|---|
| Controller / route handler | HTTP: parse and validate input, call a service, map results and errors to responses | Services |
| Service (domain logic) | Business rules: "an order can be cancelled only before shipping" | Repositories and gateways through interfaces |
| Repository / data access | Reading and writing the database | The database or ORM |
| Gateways / adapters | Talking to external systems: Stripe, email, S3 | External APIs |
Benefits: business rules are testable without HTTP or a database; switching the database or the web framework touches one layer; each file is easier to understand. Front ends have the same idea: presentational components, hooks for state and data, API client modules.
Related architectures you may hear named: clean architecture, hexagonal architecture (ports and adapters), onion architecture. All put business logic at the centre, independent of frameworks and databases, which are plugged in at the edges.
KISS and YAGNI
- KISS: Keep It Simple. The simplest solution that meets the requirements is usually the best.
- YAGNI: You Aren't Gonna Need It. Do not build features, options or abstractions for imagined future needs; build them when they are actually needed. Speculative flexibility costs time now and complexity forever.
How to say it in an interview
"DRY is about not duplicating knowledge, not about merging code that merely looks alike; the wrong abstraction, with flags and branches for every caller, is worse than duplication, so I wait for the rule of three and abstract only when I understand what varies. I prefer composition over inheritance, building services from small injected parts like a logger and a clock, and reserve inheritance for true is-a relationships. I separate concerns into controllers for HTTP, services for business rules, repositories for data and adapters for external systems, which keeps the core testable. And I keep things simple and avoid building for imagined needs."
Key words
| Word | Meaning |
|---|---|
| DRY | Each piece of knowledge has one authoritative place |
| Wrong abstraction | Shared code forced to serve diverging needs |
| Rule of three | Abstract on the third repetition |
| Composition | Building behaviour by combining parts |
| Separation of concerns | Each part handles one responsibility |
| Layered architecture | Controllers, services, repositories, adapters |
| KISS / YAGNI | Keep it simple / you aren't gonna need it |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.