Code quality and the full request
We close with the habits that keep backend code changeable and then trace one request through everything in the unit. Interviews often move from architecture straight into code, and the same principles decide whether a codebase is still pleasant to change in three years. We will cover separation of concerns and dependency inversion, side effects, immutability and resource ownership, when abstraction pays for itself, and Wren’s POST /orders end to end.
#Section 36Separation of concerns, dependency inversion and interface design
Separation of concerns means each piece of code deals with one reason to change. Wren’s pricing function changes when the business changes its discount rules. The repository changes when the database schema changes. The controller changes when the API changes. Mixing them means a schema change forces a careful reread of pricing logic, and a pricing change risks breaking SQL. The layering from Part VII is separation of concerns applied at the scale of a request.
Dependency inversion, the “D” in Robert Martin’s SOLID principles, says that high-level policy should not depend on low-level detail. Both should depend on an abstraction owned by the policy. OrderService does not import StripeClient. It declares the PaymentGateway interface it needs, charge(order_id, amount, key) -> PaymentResult, and StripeGateway implements it. When Wren adds Razorpay for Indian cards, it writes a second implementation and changes one line of wiring. The service and its tests do not change.
Good interface design follows from what the caller needs, not from what the implementation happens to offer. A payment gateway interface with one charge method and one refund method is easy to fake, easy to implement twice, and hard to misuse. An interface that mirrors all 200 endpoints of Stripe’s SDK is neither. Prefer composition over inheritance. A service that holds a gateway, a repository and a clock is easier to understand than one that inherits behaviour through four base classes, because everything it can do is visible in its constructor.
Naming is part of design. OrderService.place(order) tells a reader what happens. OrderManager.process(data) tells them nothing. Names should come from the business vocabulary, the words restaurant staff and product managers actually use, so code, tickets and conversations talk about the same things.
#Section 37Side effects, immutability, resource ownership and when abstraction pays
A side effect is anything a function does besides returning a value: writing to the database, sending an email, charging a card, logging, reading the clock. Side effects are necessary, since a backend exists to cause them, but they are what makes code hard to test and reason about. A useful habit keeps business decisions in pure functions, which compute a result from their inputs alone, and pushes effects to the edges. Wren’s price(basket, menu, coupon, now) is pure and trivially testable with any inputs. The service gathers its inputs, calls it, and then performs the effects in a transaction. This arrangement is sometimes called “functional core, imperative shell”.
Immutability helps the same way. A value that cannot change after creation can be shared between threads without locks and passed to functions without fear that they modify it. Domain events and DTOs are natural immutable values. Mutable shared state, such as a module-level dictionary used as a cache, is a common source of concurrency bugs and of test pollution across runs.
Resource ownership is the question of who opens and who closes. A database connection, a file handle, a lock or an HTTP response body must be released exactly once, on every path, including errors. Languages provide structured forms for this, such as Python’s with, Java’s try-with-resources, Go’s defer and Rust’s ownership rules. The function that acquires a resource should release it, and resources should not be passed around in ways that make it unclear who is responsible. Unit IX shows the outages that leaked connections cause.
Finally, every abstraction costs something to read, write and change, and it pays back only when it is used. An interface with one implementation that will never have a second, and is never faked in a test, is pure cost. A rough rule is to write the concrete code first, extract the abstraction when the second real use appears, and accept a little duplication rather than the wrong abstraction. As an illustrative model, the cost of change without an abstraction grows quickly with the number of implementations and call sites, while with one it starts higher and grows slowly. The lines cross somewhere around the second implementation.
#Section 38POST /orders through the whole architecture
User 42 taps “Place order” for one biryani from restaurant 9. The app sends POST /orders with an Idempotency-Key, a bearer token and a JSON body. The router matches the path to OrderController.create. Middleware assigns request id req_7Hq2, enforces the body limit and the user’s rate limit, authenticates the token, and resolves the tenant. The controller parses the body into CreateOrderRequest, which rejects unknown fields and bounds quantities, returning 422 with field errors if anything is off.
Next, the idempotency layer from Part IV inserts the key with status running. If the key already exists with a stored response, the controller returns that response immediately. Then the controller calls OrderService.place(user, request). The service loads the restaurant and menu through repositories, checks that restaurant 9 is open and the items are available, and calls the pure price() function with the current time from an injected clock. It opens a transaction, inserts the order through the repository, records the idempotency response, and writes an outbox event, which Unit VIII uses to notify the kitchen. It commits.
If anything fails, the error travels up wrapped with context and the global handler maps it. A closed restaurant becomes 409 RESTAURANT_CLOSED, a database outage becomes 503 with Retry-After, and an unexpected exception becomes a generic 500 with an alert and a logged cause chain. On success the controller maps the domain Order to OrderResponse and returns 201 Created with Location: /orders/124. Every log line along the way carries req_7Hq2.
Each piece of the unit plays a part in that one request. Resource URLs and status codes make it predictable. Idempotency keys make it retryable. The contract fixes its shape for every client. Layers and ports give each concern a home that can be tested alone. The error model makes failures honest and actionable. Tests at each level prove it works. What this unit did not cover is what happens inside the repository, how connections, transactions, ORMs and migrations behave under load. Unit VI opens that box.