software-engineer-blog logoSoftware Engineer Blog

Module 10 · Software design

Unit 40 of 49

Unit 40 · Module 10 · Software design

Layers: route handler, service, repository

The rule for publishing an article ends up in four places, and one never gets the fix.

Unit 40 of the free 49-unit computer-science course, in software design. 1 topic to watch or read, 2 interview questions answered in full and a short self-check.

Watch or read

One topic makes up this unit. Take each one whichever way suits you, then answer the questions below.

Route handler vs service vs repository

The rule for publishing an article ends up in four files — the web handler, a nightly job, a CLI, a webhook — and one of them never gets the fix. This is the whole extraction, line by line: what belongs in the handler, what belongs in the...

ReelRead

Interview questions this unit unlocks

Asked out loud, answered out loud. Read the answer, then say it in your own words.

Where does business logic belong — the route handler, a service, or the repository?

The service. A route handler translates HTTP into a call — parse, validate the shape, map the result to a status code — and should be readable in one screen with nothing worth unit-testing in it. A repository translates between the domain and the database and knows no rules. The service is the only layer that knows what the business means, which is why it is the only one whose tests survive swapping the web framework or the database.

The tell that the split has gone wrong: a transaction spanning two repository calls with a rule between them, sitting in a controller. That rule belongs one layer down.

Is that not just extra indirection for a small app?

Often, yes — and the honest answer is that the layers earn their keep at the point a second caller appears. The moment the same operation has to run from an HTTP route, a background job and a CLI command, logic living in the handler is either duplicated or reached for through the web framework. Until then, one file with a clear function is fine, and pretending otherwise is architecture as decoration.

Self-check — 3 questions

Answer alone, at 2am, with no interviewer in the room.

Part of Everything You Need to Know About Computer Science.