Architectural Patterns and Anti-Patterns Questions
Architecture-level patterns and the anti-patterns that signal a wrong turn. Patterns: layered and n-tier architecture, including where cross-cutting concerns like authentication, rate-limiting and tracing belong, dependency injection trade-offs, and thin-versus-fat controller design; hexagonal (ports and adapters) and clean architecture; CQRS and event sourcing; backend-for-frontend; plugin (microkernel) extension models; and the coupling, cohesion, encapsulation and separation-of-concerns principles behind them, including when each applies and what it costs. Anti-patterns: distributed monolith, chatty services, shared-database coupling, cyclic service dependencies, leaky abstractions that expose internal schemas, and golden-hammer pattern adoption. Covers the detection signals (deploy coupling, call-graph fan-out, change amplification, trace evidence), incremental remediation, and architecture governance that keeps smells from recurring. This is about diagnosing and fixing the smell in an existing design, not the monolith-versus-microservices decision itself.
What's the difference between loose and tight coupling between services, and why does it matter for how independently teams can ship? Name a few concrete techniques you'd use to loosen coupling in an existing tightly-coupled system, and describe how you'd actually measure or surface coupling levels across a codebase or service map today.
Sample Answer
Direct answer
Two services are tightly coupled when one cannot change, deploy or even stay up without the other: it depends on the other's internal details (field names, database tables, timing, availability). They are loosely coupled when each depends only on a small, stable, published contract and can tolerate the other being slow, down, or on a different version. It matters for shipping because coupling decides the unit of release: if Team A's change forces a change or a coordinated deploy in Team B's service, the two teams move at the speed of their slowest shared calendar. To loosen coupling I use stable versioned contracts, events instead of synchronous calls where the caller does not need an immediate answer, and each service owning its own data. To measure it I combine three views: the static dependency graph, the runtime call graph from traces, and change history.
The kinds of coupling (it is not one thing)
| Kind | Tight looks like | Loose looks like |
|---|---|---|
| Contract | Consumer reads the provider's internal data shape or table | Consumer depends on a documented, versioned API or event schema |
| Temporal (runtime) | Caller blocks until callee responds; callee down means caller down | Caller publishes an event or enqueues work and moves on |
| Deployment | Releases must happen together or in order | Either side ships alone; old and new versions coexist |
| Data | Two services write the same table | Each service owns its data; others get copies via events or ask through the API |
| Knowledge | Consumer duplicates the provider's business rules | Consumer asks for the decision, not the rule |
A useful mental model: coupling is the number of things the other side could change that would break you. Loosening coupling shrinks that list.
Techniques to loosen an existing tightly coupled system
- Put an explicit, versioned contract in front of every dependency. Replace direct table reads with an API or event, version it, and make changes additive only (add fields, never rename or remove in place).
- Consumer-driven contract tests. Each consumer declares the fields and behaviours it relies on; the provider runs those checks in its own build, so it learns before deploying whether it breaks anyone. This is what lets deploys become independent.
- Move from synchronous calls to events where no immediate answer is needed. The publisher announces a fact ("OrderPlaced") and does not know or care who listens.
- Give each service its own data, with local read copies. If Shipping needs a customer's address, it keeps its own copy updated from
CustomerAddressChangedevents instead of calling Customer on every shipment. - Anti-corruption layer (a translation layer at the boundary): when you must integrate with a messy legacy model, translate it into your own model at the edge so its quirks do not spread into your code.
- Tolerant reader. Consumers ignore unknown fields and do not depend on field order, so providers can add fields freely.
Choosing between REST, event-driven and async messaging: a worked example
Scenario: an e-commerce platform where Checkout currently calls Loyalty, Email, Analytics and Inventory synchronously during order placement.
| Interaction | Does the caller need the answer now? | Choice | Why |
|---|---|---|---|
| Checkout needs to know stock is reserved before confirming | Yes, the user waits for the result | Synchronous request/response (REST, or gRPC, a binary remote-procedure-call framework) | The answer changes what the user sees; a queue would just make the user wait on a queue |
| Loyalty points, Email receipt, Analytics | No, they react to a completed order | Event-driven publish/subscribe (Checkout publishes OrderPlaced to a topic, a named channel in the message broker that any number of subscribers can listen to without the publisher knowing who or how many they are; each subscribes) | Checkout no longer knows these consumers exist; adding a fifth consumer needs zero Checkout changes |
| Generate a PDF invoice, 5 to 30 seconds of work | No, but it is a command to one specific worker | Async point-to-point messaging (a work queue) | Exactly one worker should do it, with retries and a dead-letter queue (DLQ, where messages that keep failing are parked for inspection) |
Before: order placement had 4 synchronous downstream dependencies, so an Email outage failed checkouts. After: 1 synchronous dependency (Inventory), and Email being down only delays receipts. The distinction that drives the choice is "does the caller need the result to continue?" plus "is this a fact for anyone, or a command for one worker?".
Measuring coupling across a codebase or service map
View 1: static dependency graph (what the code declares)
Build the graph of which service or module depends on which, from build files, imports or client libraries. For each node compute:
- Ca (afferent coupling): how many others depend on it.
- Ce (efferent coupling): how many it depends on.
- Instability I = Ce / (Ca + Ce), from 0 (everyone depends on it, it depends on nothing) to 1 (it depends on everything, nothing depends on it).
Example: Checkout depends on 6 services and 2 depend on it, so I = 6 / (2 + 6) = 0.75, close to 1 (fully unstable). That is fine for a top-level orchestrator (a service like Checkout that coordinates a business process by calling out to several others, rather than being called deep inside someone else's process): nothing else in the system depends on it in any deep way (Ca = 2 is low), so a change to Checkout has nowhere further outward to ripple; being "unstable" just means it is free to change because it sits at the edge of the graph, not the centre.
The warning sign is a shared service everyone depends on (high Ca) that also has high Ce, and it is worth working a number for: suppose a shared Pricing service has Ca = 8 (eight other services call it) and Ce = 5 (it itself calls five other services or data sources, for tax rates, currency conversion and so on). Its instability is I = 5 / (8 + 5) ≈ 0.38, a middling number that looks unremarkable if you only glance at I. The two raw counts are the real story: high Ca means eight other services need to change, or at least be retested, whenever Pricing's contract changes (hard to change safely), and high Ce means Pricing itself is exposed to five other services' changes rippling into it (likely to change often). A healthy shared service instead aims for high Ca with low Ce, an I closer to 0.1-0.2: many dependents, but few dependencies of its own that could knock it over. Also flag cycles in this graph; every cycle is a set of services that can no longer be released in any safe order.
View 2: runtime call graph (what actually happens)
Distributed tracing, instrumentation that tags every call belonging to one request with a shared id so the calls across every service can be reassembled afterward into one end-to-end record (for example OpenTelemetry, an open standard for doing this), records every call a request makes. From traces, build the live service map and track per endpoint:
- Fan-out: downstream calls per inbound request.
- Synchronous depth: longest chain of blocking calls.
This catches coupling that static analysis misses, such as calls built from configuration, or a service calling another 40 times in a loop.
View 3: change history (how the code actually evolves)
From version control, compute temporal coupling: how often two services change in the same ticket or release. High temporal coupling with no declared dependency is the most interesting finding, because it means a hidden dependency (a shared schema, a duplicated rule).
Put all three on one dashboard. Each alone misleads: the static graph shows declared dependencies, traces show runtime behaviour, history shows what actually slows teams down.
Trade-offs and pitfalls
- Loose coupling has a price. Events give you eventual consistency (subscribers see the change a little later), harder debugging across asynchronous hops, and message schemas that still need versioning. Use them where decoupling is worth that, not everywhere.
- Async is not automatically loose. An event that carries the publisher's full internal entity couples every subscriber to that entity's shape.
- Over-abstracting. A generic "universal integration layer" in front of everything becomes its own tightly coupled god component: one component that has absorbed so much shared responsibility that everything else ends up coupled through it.
- Cohesion is the other half. Low coupling between services only helps if each service is cohesive (its parts belong together). Splitting a cohesive unit apart raises coupling, however many events you add.
Describe a typical three-tier (multi-tier) layered web architecture: presentation/UI, application/business logic, and persistence/data. For each tier, name its responsibilities, then trace how a single request flows through the system, from the client through ingress, load balancing, and the application tier down to the data tier and back. What are the trade-offs of this architecture (scalability, deployment complexity, testability) compared to a simpler two-tier design or a flatter, event-driven one?
Sample Answer
Direct answer
A three-tier architecture splits a web application into three independently deployed parts: the presentation tier (what runs in or is sent to the user's browser or app), the application tier (the servers that apply business rules) and the data tier (the databases and stores that keep state). Each tier talks only to its neighbour, so the browser never touches the database directly. You pay for an extra network hop and more moving parts, and in exchange you get a stateless middle tier you can scale by adding servers, one place to enforce security and rules, and parts you can test and deploy separately.
A useful distinction up front: a tier is a physical deployment unit (separate machines or containers), while a layer is a logical grouping of code inside one program. Three-tier is about tiers.
The three tiers and what each owns
| Tier | Responsibilities | Typical technology | Should NOT do |
|---|---|---|---|
| Presentation | Render screens, capture input, client-side validation for fast feedback, call the API | React or server-rendered HTML, mobile app, static assets on a CDN (content delivery network: servers near users that cache files) | Hold business rules or database credentials |
| Application | Authenticate and authorize, validate input authoritatively, apply business rules, coordinate transactions, call other services, shape responses | Stateless API servers (Java, Go, Node, Python) behind a load balancer | Keep user session state in local memory (breaks horizontal scaling) |
| Data | Store and retrieve durable state, enforce integrity (keys, constraints), run indexed queries, replicate and back up | PostgreSQL or MySQL, plus a cache such as Redis and object storage for files | Encode business workflows in stored procedures that nobody can test |
Tracing one request: GET /orders/123
- Client. The browser already loaded the presentation code from the CDN. The user opens "My orders", and the JavaScript sends
GET /api/orders/123over HTTPS with a session token. - Ingress and load balancing. DNS resolves the API hostname to a load balancer (or, in Kubernetes (a container-orchestration system: software that runs and manages many server instances across a fleet of machines for you, restarting failed ones and scheduling new ones), an ingress controller: the component that admits outside traffic into the cluster). It terminates TLS (decrypts HTTPS), checks which application instances are passing health checks (a periodic ping each instance must answer, so the load balancer stops sending traffic to one that has stopped responding), and forwards the request to one of them.
- Application tier. The chosen instance validates the token, checks the rule "a customer may only read their own orders", and asks its data-access code for order 123. It may check a cache first.
- Data tier. A connection is borrowed from the instance's connection pool (a set of already-open database connections the instance keeps ready, so a request reuses one instead of paying the cost, tens of milliseconds, of opening a fresh connection to the database each time), an indexed
SELECTruns against the orders table, and rows come back. - Back up the chain. The application maps rows to a JSON response (dropping internal columns), returns 200, the load balancer relays it, and the browser renders the page.
sequenceDiagram
participant B as Browser
participant LB as Load balancer
participant App as App server
participant DB as Database
B->>LB: GET /api/orders/123 over HTTPS
LB->>App: forward to a healthy instance
App->>App: check token and ownership rule
App->>DB: SELECT order 123
DB-->>App: rows
App-->>LB: 200 JSON
LB-->>B: 200 JSON
Because step 3 keeps no per-user state in memory, any instance can serve the next request from the same user. That property is what lets the middle tier scale out.
Worked example: where the bottleneck moves
Suppose peak load is 1,200 requests per second (RPS) and a load test shows one application instance sustains about 150 RPS.
- Instances needed: 1,200 / 150 = 8. Run 10 so that losing one or two still leaves capacity (25% headroom).
- Each instance keeps a database connection pool of 20 connections: 10 x 20 = 200 connections.
- PostgreSQL's
max_connectionsdefault is typically 100 (the documentation notes it can be lower if kernel settings do not support 100).
So the design that scales the application tier by adding boxes will exhaust the data tier at peak, exactly when the autoscaler (the system that automatically adds or removes application instances based on load) adds instances. Fixes: shrink each pool (10 x 8 = 80 connections), or put a connection pooler such as PgBouncer between the tiers: a lightweight service that holds a smaller, fixed number of real connections to Postgres and multiplexes many application-side requests through them. PgBouncer's own default is session pooling, which hands one real connection to an application connection for its whole session and would not shrink the connection count here; the setting this design actually needs is transaction pooling mode, which hands a connection out per transaction and takes it back the instant that transaction commits or rolls back, then reuses it for the next request. PgBouncer also offers a statement pooling mode that returns the connection after every individual query, but that mode explicitly disallows transactions spanning multiple statements, which would break a multi-step operation like a funds transfer, so transaction mode, not the default and not statement mode, is the setting to reach for. That lets the same 200 application-side connections be served through, say, 50 real database connections instead of colliding with the 100-connection ceiling. The general lesson is that the application tier scales horizontally cheaply and the data tier does not, so in a three-tier system the bottleneck usually migrates to the database.
Trade-offs versus two-tier and event-driven designs
A two-tier design has the client talk straight to the database (a desktop app with a database driver, or a small server-rendered app where UI code and SQL live in one process). An event-driven design has components publish events ("OrderPlaced") to a broker such as Kafka (a system dedicated to durably queueing and delivering these events to every interested component, so the publisher does not need to know who is listening or whether they are online right now), and other components react asynchronously instead of being called directly.
| Dimension | Two-tier | Three-tier | Event-driven |
|---|---|---|---|
| Scalability | Every client holds database connections; the database takes all load | Stateless middle tier scales out; the database remains the limit | Consumers scale independently; the broker absorbs spikes |
| Deployment complexity | Lowest: one app plus a database, but rolling out a desktop client means updating every install | Moderate: load balancer, app fleet, database, each with its own deploy | Highest: broker, topics, consumers, schema versioning for events |
| Testability | Rules mixed with UI or SQL are hard to test in isolation | Business rules testable in the application tier without a UI | Each consumer testable alone, but end-to-end flows are hard to test and debug |
| Security | Database credentials sit on or near the client | Database reachable only from the app tier | Must also secure the broker and every topic |
| Time to market | Fastest for small internal tools | Reasonable default for most web products | Slowest to start; pays off when work can happen later |
| Failure behaviour | Database down means everything is down | A slow database slows every request synchronously | A slow consumer builds a backlog but the user-facing request still succeeds; data is eventually consistent (other parts catch up after a delay) |
Recommendation. Use three-tier as the default for a customer-facing web product. Use two-tier only for small internal tools with a handful of trusted users. Add event-driven pieces for work the user does not need to wait for (emails, search indexing, analytics), which gives a hybrid: synchronous three-tier for the request path, events for side effects. What would flip this: if most work is naturally asynchronous (ingesting sensor data, processing uploads), an event-driven core is the better starting point.
Pitfalls that separate strong answers
- Stateful application servers. Sessions kept in instance memory force "sticky" routing (the load balancer must keep sending one user to the same instance every time, because that instance is the only one holding their session in memory), and users get logged out when an instance dies. Keep sessions in a token or a shared store.
- A pass-through middle tier. If the application tier only forwards requests to SQL, you paid for a hop and got nothing; the rules have leaked into the client or into stored procedures (business logic written and run inside the database itself, rather than in the application tier).
- Confusing tiers with layers. Splitting every code layer onto its own network hop adds latency without adding isolation you need.
- Forgetting that tiers fail together. In a synchronous chain, a slow data tier makes the whole request slow; the architecture does not isolate that by itself.
Describe encapsulation in the context of service APIs and data models. Explain how exposing internal data structures (for example, database-schema details) in service responses can lead to production issues, and how stronger encapsulation would have prevented them. Include one example of an enforcement mechanism.
Sample Answer
Direct answer
Encapsulation for a service means clients see a deliberate, stable contract (the fields and behaviour the service promises) and never the internal representation behind it (table names, column names, database IDs, internal status codes, ORM objects). When a service serialises its database rows straight into API responses, every client silently couples to the schema, so an ordinary internal change such as a column rename or a table split becomes a breaking change in production, and fields that were never meant to leave the service leak out. The fix is an explicit response model that the service owns and maps to, with an automated check that stops internal types from reaching the wire.
How schema leakage causes production issues
Suppose an orders endpoint returns the ORM (object-relational mapping) entity directly:
{
"ord_id": 88213,
"cust_fk": 4411,
"status_cd": 3,
"tot_amt_cents": 12999,
"deleted_at": null,
"internal_fraud_score": 0.82,
"customer": { "id": 4411, "password_hash": "..." }
}
Each of those fields is a future incident:
- Renames break clients. A developer renames
tot_amt_centstototal_centsin a routine migration. The web app is redeployed the same day, but installed mobile app versions keep readingtot_amt_centsand show a blank or zero total until every user updates, which can take weeks. - Internal codes become a public contract. Clients hard-code
status_cd == 3to mean "shipped". The team later inserts a new status "packed" as 3 and renumbers the rest, and every client now shows the wrong state. - Sensitive data leaks.
internal_fraud_scoreand a lazily loadedcustomer.password_hash(the ORM fetches a related row, here the customer, only when code actually touches it rather than upfront, so merely serialising an order can silently trigger the query that pulls it in) were never meant to leave the service, but serialising the whole entity sends them anyway. - Write-side over-posting. If the same entity is also accepted as input, a client can send
"status_cd": 3or another privileged field and the framework will happily bind it (often called mass assignment). - Performance surprises. Serialising an entity walks its relationships (turning the object into JSON touches every related object, and each one that is lazily loaded triggers a fresh database query the first time it is touched, rather than being fetched upfront), so adding a new relationship to the model can suddenly trigger dozens of extra queries or a huge payload for every response.
- Physical IDs leak. Exposing sequential database keys lets anyone enumerate records and makes it painful to re-key or merge databases later.
The pattern behind all six: the service gave away the right to change its own internals.
What stronger encapsulation looks like
The same endpoint returning a contract the service owns:
{
"id": "ord_7Kq2Lm",
"customer_id": "cus_9Qa1",
"status": "shipped",
"total": { "amount": "129.99", "currency": "USD" }
}
- Stable external IDs (opaque strings) instead of database keys.
- Named enum strings ("shipped") instead of internal numeric codes.
- Only fields that clients need, chosen on purpose; nothing sensitive is reachable.
- A mapping function between the internal entity and this response model. When the column is renamed, one line in the mapper changes and the response is identical.
Applied to each earlier failure: the rename touches only the mapper (1), the enum stays "shipped" whatever the database stores (2), the fraud score and password hash are not on the response type so they cannot be serialised (3), requests bind to a separate input model that has no status field (4), the mapper reads only what it needs (5), and external IDs hide the physical key (6).
An enforcement mechanism
My choice is an architecture test in CI that forbids API handlers from returning or accepting persistence types. For example, in a Java service an ArchUnit rule states that classes in the ..api.. package may not depend on classes in the ..persistence.entity.. package; in Python, an import-linter contract does the same between the API module and the models module. A developer who takes the shortcut gets a red build, not a code-review debate.
Two complementary checks make it stronger:
- Contract checking: the response schema is written in an OpenAPI document (a machine-readable API description), responses are validated against it in tests, and a breaking-change diff tool runs on every pull request so removing or renaming a public field is flagged.
- Consumer-driven contract tests: each client publishes the fields it actually uses, and the provider's build fails if a change would break one of them.
Trade-offs and pitfalls
- Mapping boilerplate is the real cost. It is worth it on any API with external or independently deployed clients; for a throwaway internal admin tool it may not be.
- Mirror DTOs (data-transfer objects that copy every column one-for-one) give the look of encapsulation with none of the benefit. The response model should be designed from what clients need.
- Leaking through errors: raw database error messages ("duplicate key violates constraint orders_pkey") expose the schema just as effectively. Map errors to stable error codes too.
- Leaking through query parameters: letting clients sort or filter by arbitrary column names (
?sort=tot_amt_cents) couples them to the schema through the request instead of the response.
Discuss the trade-offs between keeping controllers thin (pushing logic into services) versus allowing fatter controllers that orchestrate use cases directly. When is the thin-controller approach clearly preferable, and what organizational or technical constraints might make fatter controllers an acceptable choice?
Sample Answer
Direct answer
Default to thin controllers: the controller parses the request, calls one application-service (use-case) method, and maps the result to a response, while the business logic lives in the service. That default is clearly right as soon as the same logic is reachable from more than one entry point or carries rules worth unit testing. A fatter controller, one that orchestrates the use case itself (calls repositories, applies rules, sends notifications), is an acceptable, deliberate choice for simple CRUD (create, read, update, delete) endpoints with no real rules, for code with a known short life, and for single-entry-point handlers, provided the team knows the trigger that will force a refactor.
The forces in tension
| Force | Favours thin controllers | Favours fatter controllers |
|---|---|---|
| Reuse | Logic needed by HTTP, queue consumers, batch jobs, CLI | Exactly one entry point, now and foreseeably |
| Testability | Rules testable without an HTTP request or web framework | Little logic to test; framework integration tests suffice |
| Readability | Each class has one reason to change | Whole flow readable in one place, no jumping across files |
| Speed of delivery | Small upfront cost per feature | Fastest for prototypes and admin screens |
| Consistency with codebase | Existing code is layered | Existing framework convention puts logic elsewhere (for example Rails, a popular web framework, keeps logic in models) |
When thin is clearly preferable
- Two or more entry points. The same "place order" rule is triggered by the web API, a mobile API version, a CSV import job and a message consumer.
- Non-trivial rules. Pricing, eligibility, state transitions, money movement.
- Transactions spanning several writes. The unit of work belongs in one testable place, not spread across request-handling code.
- Long-lived product code with several teams. Clear seams (well-defined boundaries between pieces of code, each with one clear responsibility) reduce merge conflicts and review load.
When a fatter controller is acceptable
Technical constraints
- The endpoint is CRUD over one table with validation only; a service method would just forward the call.
- A serverless function (a cloud-run function that only executes in response to one triggering event, with no server process of your own to manage) handles a single event type and has one caller; the handler is the use case.
- The framework already provides the layering you would build (validation annotations that declare a field's rules directly on the model, model callbacks that run code automatically before or after a save), and adding a service layer would duplicate it.
Organizational constraints
- A prototype or experiment with an agreed deletion or rewrite date.
- A small team where consistency with the existing codebase's conventions matters more than a locally better structure; mixing two styles in one codebase is worse than either.
- Internal admin tools whose failure is cheap and whose users are a handful of staff.
In every case, write down the trigger that ends the exception: "the first time this logic is needed outside this controller, extract it."
Worked example: the second entry point
An order-placement controller has grown to about 120 lines: it validates stock, applies a discount rule, writes the order, reserves inventory and sends an email. Over the next two quarters the team adds a bulk CSV import job, a mobile API version and a consumer for marketplace orders from a message queue. That is 4 entry points.
- Option A, copy the logic. Four copies of the discount rule. When finance changes the rule, the fix lands in 2 of the 4 copies, and marketplace orders keep the old discount for weeks. Nobody notices because each copy has its own tests.
- Option B, extract a
PlaceOrderuse case. One class with the rule and one set of unit tests; four thin adapters (small pieces of code, one per entry point, whose only job is translating that entry point's input into the call the use case expects). The discount change is one edit.
The cost of thin-from-the-start was a single extra class. The cost of fat-then-duplicated was a pricing defect. That asymmetry is why thin is the default once reuse is plausible, and why a CRUD admin screen, where reuse is implausible, is the right place to skip it.
Pitfalls on both sides
- Over-thin: the pass-through service. Every controller method calls a service method with the same name that calls a repository method with the same name. Three layers, zero logic. If a service method has no rule or orchestration, let the controller call the repository for that endpoint, or collapse the layer for that module.
- Business rules in request validation. "Amount must be a number" is controller work; "amount must not exceed the credit limit" is a rule, even though both look like validation.
- Fat service, not thin controller. Moving 120 lines into one
OrderServicewith 30 methods trades a fat controller for a god class (a single class that has taken on far too many responsibilities and knows too much about the system). Organize by use case, one class or function per operation. - HTTP types leaking into services. A service that takes a request object or returns a status code has not actually been separated; it cannot be called from the queue consumer.
Explain dependency injection (DI) and the differences between constructor injection, setter injection, and the service-locator approach. When designing a layered backend, what are the advantages and the potential pitfalls of leaning on a DI framework in your service and repository layers?
Sample Answer
Direct answer
Dependency injection (DI) means an object receives the collaborators it needs (a repository, a clock, an HTTP client) from outside, instead of creating or looking them up itself. Constructor injection passes required dependencies as constructor arguments, so the object is complete the moment it exists. Setter injection assigns dependencies after construction through setter methods, which suits optional ones. A service locator is the opposite direction: the object asks a global registry for what it needs at run time, which hides its dependencies. Use constructor injection by default, setters only for genuinely optional dependencies, and keep service locators out of business code.
The three approaches compared
| Constructor injection | Setter injection | Service locator | |
|---|---|---|---|
| How dependencies arrive | Constructor parameters | Setter methods after construction | Object calls Registry.get("x") itself |
| Are dependencies visible? | Yes, in the signature | Partly (must read the setters) | No, buried in method bodies |
| Can the object exist half-built? | No | Yes, until every setter runs | Looks complete, fails later |
| Immutability | Fields can be final or read-only | Fields must stay mutable | N/A |
| When a dependency is missing | Fails at construction (or at application startup with a container) | Null reference at first use | Lookup error at first call, possibly in production |
| Good for | Required collaborators | Optional collaborators with a sensible default | Framework glue at the edge of the application |
Some frameworks also allow field injection (the container writes directly into a private field). It hides dependencies like a locator does and makes plain unit testing awkward; Spring's own reference documentation recommends constructor injection for mandatory dependencies and setters for optional ones.
Worked example: why hidden dependencies hurt
This runnable Python program builds the same service two ways.
class Registry: # a service locator: a global lookup table
_services = {}
@classmethod
def register(cls, name, obj):
cls._services[name] = obj
@classmethod
def get(cls, name):
return cls._services[name]
class OrderServiceWithLocator:
def total(self, order_id):
repo = Registry.get("order_repo") # hidden dependency
return sum(repo.line_amounts(order_id))
class OrderServiceWithConstructor:
def __init__(self, repo): # dependency is visible in the signature
self.repo = repo
def total(self, order_id):
return sum(self.repo.line_amounts(order_id))
class FakeOrderRepo:
def line_amounts(self, order_id):
return [1200, 350]
print("constructor:", OrderServiceWithConstructor(FakeOrderRepo()).total("o1"))
svc = OrderServiceWithLocator() # constructs fine, nothing looks wrong yet
try:
print("locator:", svc.total("o1"))
except KeyError as e:
print("locator failed at call time, missing:", e)
Registry.register("order_repo", FakeOrderRepo())
print("locator after global setup:", svc.total("o1"))
Output:
constructor: 1550
locator failed at call time, missing: 'order_repo'
locator after global setup: 1550
The constructor version tells you from its signature that it needs a repository, and a test simply passes a fake (1,200 + 350 = 1,550). The locator version constructs without complaint and fails only when total runs; to test it you must mutate global state, which leaks between tests that run in the same process.
Advantages of a DI framework in the service and repository layers
- Wiring large object graphs. A container (Spring, .NET's built-in container, Guice, Dagger) builds hundreds of objects in the right order so you do not hand-write the assembly code.
- Lifecycles and scopes. It manages which objects are shared for the whole application (singleton), created per request, or created each time.
- Environment-specific configuration. Swap the real payment client for a sandbox client in staging through configuration, not code changes.
- Declarative cross-cutting behaviour. Transactions or metrics applied by annotation (a marker attached to code, such as
@Transactional, that tells the framework to wrap it with extra behaviour automatically) around service methods. - Testability. Because services receive their repositories, tests hand them fakes, and the business logic never needs a database to be exercised.
Pitfalls to watch for
- Framework leaking into the core. Annotations and container types in domain classes couple your business rules to the framework; hexagonal and clean architecture (architectural styles that keep business rules as plain code with no framework dependencies, pushing frameworks, databases and other details to the outside) both require that dependencies point inward, toward framework-free code. Keep the core as plain objects and do the wiring in one composition root (the single place at startup where the object graph is assembled).
- Scope mismatch. A singleton service that receives a request-scoped object (one the container creates fresh for each incoming request and discards afterward) at startup keeps that one instance forever, so data from one request can bleed into another. Containers offer proxies (a lightweight stand-in injected into the singleton that, on every call, fetches whichever request-scoped instance is current) or providers (a small factory object injected instead of the real dependency, which the singleton calls each time it needs a fresh, current instance) for this; you have to know to use them.
- Circular dependencies. With constructor injection, a cycle (A needs B, B needs A) cannot be constructed and the container fails at startup, which is good: it exposes a design problem. Setter or field injection can let the container paper over the cycle.
- Hidden god classes (classes that quietly accumulate far more responsibility than they should, because adding one more dependency is so easy). Adding a dependency costs one more constructor parameter, so bloat creeps in silently. A service with 10 or more injected collaborators is a cohesion smell (a warning sign that a class is doing too many unrelated things to be well designed); split it.
- Magic and startup cost. Classpath scanning (the container inspecting every class in the application at startup to find the ones it should manage) and reflection (code that inspects or calls into other code at run time, by name, rather than at compile time) make it hard to answer "where does this object come from?" and slow startup, which matters for serverless (functions that start fresh for each invocation and shut down between them, so every millisecond of startup cost is paid repeatedly) or short-lived processes. Compile-time DI (Dagger) (wiring code generated when the project is built, instead of discovered by scanning and reflection at startup) or plain manual wiring avoids both.
- Interfaces for everything. Creating an interface for every class "for DI" adds ceremony. Introduce an interface where there is a real second implementation or a test double worth having.
Recommendation: constructor injection everywhere in service and repository code; a container only at the outer layer; plain manual wiring for small services, where a 20-line composition root is clearer than a framework.
Unlock Full Question Bank
Get access to all 16 Architectural Patterns and Anti-Patterns interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.