- Prerequisites
- 7.1 Interfaces · 7.3 Composition · 5.2 Abstraction
- Covers
- Contracts · Loose coupling · Dependency inversion · Testability
- Related
- Book 4 (Spring IoC/DI) · Book 5 Vol II (DIP, ISP) · Book 7 (hexagonal and clean architecture) · Book 6 (API contracts)
On this page
1Concept / Definition
Interface-based design is the practice of making components depend on interfaces that describe what they need, rather than on the concrete classes that provide it. Each component receives its collaborators from outside — typically through its constructor — and interacts with them only through their contracts. The result is a system of loosely coupled parts that can be changed, replaced and tested independently.
It combines three ideas from this volume: abstraction (5.2) to define contracts, polymorphism (6.3) to call implementations through them, and composition (7.3) to assemble components from collaborators.
2Why It Exists
In a system where each class creates and depends on concrete classes, every change ripples: replacing a database driver touches business logic, testing a service needs a real payment provider, and one team's refactoring breaks another's code. Interface-based design localises change by putting stable contracts between parts. It is what makes dependency injection, mocking, plugin systems, and hexagonal architecture possible.
3Core Concepts
Contracts
The interface is the contract between a component and its collaborators: method signatures plus documented semantics — what inputs are valid, what is returned, which exceptions are thrown, what side effects occur. A precise contract lets each side change independently; a vague one forces each side to know how the other is implemented, defeating the purpose. Contract tests (5.2) make the semantics executable.
Loose coupling
Coupling measures how much one component must know about another. A component that creates its own MySqlOrderDao knows the concrete class, its constructor and its configuration. A component that receives an OrderRepository knows only a contract. Loose coupling means changes behind the contract — a new database, a cache, a remote call — require no change to the component.

Dependency inversion
The Dependency Inversion Principle (Robert C. Martin) has two parts: high-level modules should not depend on low-level modules — both should depend on abstractions; and abstractions should not depend on details — details should depend on abstractions. The key move is that the interface belongs to the high-level module: the business service defines OrderRepository in terms of its needs, and the persistence code implements it. Source-code dependencies then point from infrastructure towards the business core, the opposite of the flow of control.


Dependency inversion (a design principle) is often confused with dependency injection (a technique) and inversion of control (a framework style). Injection is how implementations are supplied to components that follow DIP; an IoC container such as Spring automates that injection.
| Term | What it is | Example |
|---|---|---|
| Dependency Inversion Principle | Design rule: depend on abstractions owned by the policy | OrderService depends on its own OrderRepository interface |
| Dependency Injection | Technique: supply dependencies from outside | new OrderService(jpaRepository) or constructor injection |
| Inversion of Control | Framework calls your code and manages object creation | Spring container creates and wires beans |
Testability
A component that depends on interfaces can be tested with test doubles: fakes (simple working implementations such as an in-memory repository), stubs (return fixed answers) and mocks (verify interactions). Unit tests then run in milliseconds without databases, networks or external providers, and failure scenarios that are hard to reproduce with real systems — timeouts, declined payments — are easy to simulate.

4How It Works Internally
At run time interface-based design is ordinary polymorphism: interface calls are dispatched to the injected implementation and inlined by the JIT when call sites are monomorphic. What matters is where objects are created. All the concrete wiring is concentrated in one place, the composition root — the main method, a configuration class, or a DI container that reads annotations or configuration and calls constructors in the right order.

5APIs / Features / Syntax
// Domain module: owns its ports
public interface OrderRepository {
void save(Order order);
Optional<Order> findById(OrderId id);
}
public interface PaymentGateway {
Receipt charge(Money amount, PaymentDetails details);
}
public final class OrderService {
private final OrderRepository orders;
private final PaymentGateway payments;
// injection
public OrderService(OrderRepository orders, PaymentGateway payments) {
this.orders = orders;
this.payments = payments;
}
public Receipt placeOrder(Order order, PaymentDetails details) {
Receipt receipt = payments.charge(order.total(), details);
order.markPaid(receipt);
orders.save(order);
return receipt;
}
}
// Composition root: the only place that knows the concrete classes
public final class Application {
public static void main(String[] args) {
DataSource ds = DataSources.fromEnv();
OrderService service = new OrderService(
new JdbcOrderRepository(ds),
new CardGateway(System.getenv("CARD_GATEWAY_KEY")));
new HttpServer(new OrderController(service)).start(8080);
}
}6Practical Examples
Example 1 — Unit test with fakes, no framework
class InMemoryOrderRepository implements OrderRepository {
final Map<OrderId, Order> store = new HashMap<>();
public void save(Order o) { store.put(o.id(), o); }
public Optional<Order> findById(OrderId id) { return Optional.ofNullable(store.get(id)); }
}
class DecliningGateway implements PaymentGateway {
public Receipt charge(Money amount, PaymentDetails d) {
throw new PaymentDeclinedException("insufficient funds");
}
}
@Test
void declinedPaymentDoesNotSaveOrder() {
var repo = new InMemoryOrderRepository();
var service = new OrderService(repo, new DecliningGateway());
assertThrows(PaymentDeclinedException.class,
() -> service.placeOrder(sampleOrder(), sampleCard()));
assertTrue(repo.store.isEmpty());
}Why it works. OrderService sees only its two ports, so the test hands it a fake repository that keeps orders in a map and a stub gateway that always declines. The test runs in milliseconds, needs no database or provider sandbox, and checks the rule that matters, that a declined payment saves nothing, by looking at the fake's state rather than by verifying calls.
Example 2 — Mini program: one service, three wirings
Problem. Section 5 shows the ports and a composition root that uses real infrastructure. This program is the same design end to end, small enough to run: one OrderService, an in-memory repository, and three wirings in main, with a gateway that approves, one that declines, and the approving one wrapped in a logging decorator.
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class OrderApp {
// the domain owns its ports (section 5)
interface OrderRepository {
void save(Order o);
Optional<Order> findById(String id);
}
interface PaymentGateway { String charge(long paise, String card); }
record Order(String id, long paise, String receipt) {
Order paidWith(String r) { return new Order(id, paise, r); }
}
static final class OrderService { // knows only the two contracts
private final OrderRepository orders;
private final PaymentGateway payments;
OrderService(OrderRepository orders, PaymentGateway payments) {
this.orders = orders;
this.payments = payments;
}
String placeOrder(Order order, String card) {
String receipt = payments.charge(order.paise(), card);
orders.save(order.paidWith(receipt)); // only after a good charge
return receipt;
}
}
static final class InMemoryOrders implements OrderRepository { // a fake
private final Map<String, Order> store = new HashMap<>();
public void save(Order o) { store.put(o.id(), o); }
public Optional<Order> findById(String id) {
return Optional.ofNullable(store.get(id));
}
}
static PaymentGateway logged(PaymentGateway inner) { // a decorator
return (paise, card) -> {
System.out.println(" charging " + paise + " paise");
return inner.charge(paise, card);
};
}
static void place(String label, OrderService service, Order order) {
try {
String receipt = service.placeOrder(order, "4111");
System.out.println(label + ": receipt " + receipt);
} catch (IllegalStateException e) {
System.out.println(label + ": " + e.getMessage());
}
}
public static void main(String[] args) { // the composition root
var repo = new InMemoryOrders();
PaymentGateway approve = (paise, card) -> "R-" + paise;
PaymentGateway decline = (paise, card) -> {
throw new IllegalStateException("declined: insufficient funds");
};
place("approve", new OrderService(repo, approve),
new Order("A-1", 2_500, null));
place("decline", new OrderService(repo, decline),
new Order("A-2", 9_900, null));
place("logged ", new OrderService(repo, logged(approve)),
new Order("A-3", 1_200, null));
for (String id : new String[] { "A-1", "A-2", "A-3" }) {
System.out.println(id + " saved: " + repo.findById(id)
.map(o -> "paid " + o.receipt()).orElse("no"));
}
}
}approve: receipt R-2500
decline: declined: insufficient funds
charging 1200 paise
logged : receipt R-1200
A-1 saved: paid R-2500
A-2 saved: no
A-3 saved: paid R-1200Why it behaves this way. OrderService is the same class in all three runs; only the objects passed to its constructor differ. The gateways are lambdas because PaymentGateway has one abstract method. The service saves an order only after charge returns, so the declined order A-2 is never saved, the rule Example 1 tests. The logging decorator adds behaviour around the approving gateway without the service or the gateway knowing (7.3). All three services share one repository, so the final lookups see every order that was saved.
Example 3 — The same wiring with Spring
@Service
public class OrderService {
private final OrderRepository orders;
private final PaymentGateway payments;
public OrderService(OrderRepository orders, PaymentGateway payments) {
this.orders = orders; // Spring injects the single matching bean
this.payments = payments;
}
}
@Repository class JdbcOrderRepository implements OrderRepository { … }
@Component class CardGateway implements PaymentGateway { … }Why it works. With a single constructor, Spring injects its parameters without @Autowired. For each parameter type, a port, the container needs exactly one matching bean; with none or with two candidates the application fails at startup with a clear error, which is better than failing on the first request (Q13). The container has taken over the job of Application.main in section 5.
Example 4 — Ports and adapters

In hexagonal architecture (Book 7), the domain defines ports — interfaces for what it needs (driven ports: repositories, gateways) and for what it offers (driving ports: use-case interfaces). Adapters connect the outside world: REST controllers and message listeners drive the domain; JPA repositories and HTTP clients implement the driven ports. All source dependencies point inward, so the domain can be tested and evolved without any infrastructure.
Example 5 — One contract test for every implementation
Problem. Fakes make tests fast only if they behave like the real implementations. A contract test states the behaviour of a port once and runs it against every implementation: the fake, the JDBC adapter against a test database, a caching wrapper. This version, without a test framework, checks three rules of a repository port against a correct map-based implementation and a list-based one with a subtle bug.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
public class ContractCheck {
record Order(String id, int version) { }
interface OrderRepository {
void save(Order o);
Optional<Order> findById(String id);
}
static final class MapRepository implements OrderRepository {
private final Map<String, Order> map = new HashMap<>();
public void save(Order o) { map.put(o.id(), o); }
public Optional<Order> findById(String id) {
return Optional.ofNullable(map.get(id));
}
}
static final class AppendingRepository // has a subtle bug
implements OrderRepository {
private final List<Order> rows = new ArrayList<>();
public void save(Order o) { rows.add(o); }
public Optional<Order> findById(String id) {
return rows.stream().filter(o -> o.id().equals(id)).findFirst();
}
}
// the contract, written once; every implementation must pass it
static void verify(Supplier<OrderRepository> fresh) {
Map<String, Boolean> checks = new LinkedHashMap<>();
OrderRepository r = fresh.get();
r.save(new Order("A-1", 1));
checks.put("finds a saved order", r.findById("A-1").isPresent());
checks.put("unknown id is empty", r.findById("B-9").isEmpty());
r.save(new Order("A-1", 2));
checks.put("save replaces",
r.findById("A-1").map(Order::version).orElse(0) == 2);
long passed = checks.values().stream().filter(b -> b).count();
String type = r.getClass().getSimpleName();
int all = checks.size();
System.out.printf("%-20s %d/%d passed%n", type, passed, all);
checks.forEach((name, ok) -> {
if (!ok) System.out.println(" FAILED: " + name);
});
}
public static void main(String[] args) {
verify(MapRepository::new);
verify(AppendingRepository::new);
}
}MapRepository 3/3 passed
AppendingRepository 2/3 passed
FAILED: save replacesWhy it behaves this way. verify receives a Supplier, so each implementation is tested on a fresh instance and only through the interface. AppendingRepository passes the first two checks and fails the third: it adds a second row for A-1 instead of replacing the first, and findFirst returns the old version. A unit test that used this class as its fake would pass and hide the bug. With JUnit the same checks become an abstract test class whose subclasses supply the implementation, and the database adapter's subclass runs against a real database in CI (Figure 7).

7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Interfaces defined by the implementation ("header interfaces") | Contract mirrors infrastructure; DIP not achieved; changing the database changes the interface, and with it the business code | Define ports from the consumer's needs, in the consumer's module (Q6) |
| Implementation types in interface signatures (JPA entities, SDK classes) | Consumers still coupled to the detail, and a framework upgrade ripples into the domain | Use domain types in contracts; map in adapters, so the domain never imports them |
| new of concrete dependencies inside services | Hidden coupling; untestable: tests need the real database or provider, and nothing can be swapped without editing the class | Constructor injection, wired in one composition root (section 5) |
| Service locator calls inside business code | Dependencies invisible in the API; tests must configure a global registry, and missing bindings fail only at run time | Explicit constructor parameters, so every dependency is visible |
| Interfaces for everything, including value objects and utilities | Indirection without benefit: more types to read and navigate, with nothing to vary | Interfaces at variation points and boundaries only (Q8) |
| Mocking everything, testing interactions not behaviour | Brittle tests that break on every refactoring and still pass when the behaviour is wrong | Prefer fakes and state-based assertions; mock only true side effects; keep fakes honest with contract tests (Example 5) |
| Fakes that drift from the real implementation | Unit tests pass while production behaves differently, e.g. save appends instead of replacing | Run one contract test against the fake and every adapter (Example 5) |
| Infrastructure exceptions crossing the port (SQLException, an SDK's HTTP exception) | The domain must catch provider-specific errors, so the detail leaks back in | Translate them in the adapter into domain exceptions such as PaymentDeclinedException |
8Performance & Production Considerations
- Interface indirection has no measurable run-time cost in typical code; JIT inlining removes it.
- DI containers add startup time for classpath scanning and proxy creation. For fast-starting services, consider compile-time DI or AOT processing (Spring AOT, Micronaut, Quarkus), and features such as AOT caching (1.2).
- Decorators added through interfaces (retries, circuit breakers, metrics) are the standard way to add resilience in production without modifying business code.
- Run each adapter's contract tests in CI against the real dependency, a test database or the provider's sandbox, so that a change on the provider side is caught before release (Figure 7).
- Fail fast on wiring: a missing or ambiguous implementation should stop the application at startup, as Spring does by default, not fail the first request that needs it.
9Architecture & Design Considerations
Interface-based design is the object-level form of the most important architectural rule — dependencies point toward stability and policy. The same structure appears at every scale:
| Scale | Contract | Implementation | Wiring |
|---|---|---|---|
| Class | Java interface | Implementing class | Constructor injection |
| Module | Exported API package | Internal packages | Module system / DI configuration |
| Application | Ports | Adapters (DB, HTTP, messaging) | Composition root / container |
| System | Service API (OpenAPI, AsyncAPI) | Service implementation | Service discovery, gateways |
10Interview Questions & Answers
What is interface-based design?
Designing components to depend on interfaces describing what they need, receive implementations from outside, and interact only through contracts — giving loose coupling, replaceability and testability. For example, OrderService receives an OrderRepository and a PaymentGateway in its constructor and never names JdbcOrderRepository or a payment SDK.
What is loose coupling?
A low degree of knowledge between components: each depends only on the other's contract, not on its concrete class, construction or internals, so either can change without affecting the other. A quick test: can you replace the database or a provider without editing the component? If not, it is coupled to that detail.
State the Dependency Inversion Principle.
High-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions. In practice, the business layer defines interfaces that infrastructure implements.
What is the difference between dependency inversion, dependency injection and inversion of control?
Dependency inversion is a design principle about the direction of dependencies. Dependency injection is a technique for supplying a component's dependencies from outside. Inversion of control is a broader style in which a framework creates objects and calls your code; DI containers such as Spring apply IoC to perform injection.
Why is constructor injection preferred?
Dependencies are explicit and mandatory, can be final, the object is complete after construction, it can be created without a container in tests, and an excessive number of parameters exposes a class with too many responsibilities.
Who should own an interface such as OrderRepository, and why?
The consumer — the domain or application layer — so that the interface is expressed in business terms and infrastructure depends on the domain, not the reverse. If the persistence module owned it, the domain would still depend on persistence.
What are fakes, stubs and mocks, and when would you use each?
A fake is a lightweight working implementation (an in-memory repository) — good for state-based tests. A stub returns canned answers — good for simulating collaborators' responses and failures. A mock records and verifies interactions — appropriate when the interaction itself is the behaviour, such as sending an email. Overusing mocks makes tests brittle.
Does interface-based design mean every class needs an interface?
No. Interfaces belong at boundaries and variation points: infrastructure, external services, policies that vary, module APIs. Value objects, entities and internal helpers usually do not need them; adding interfaces everywhere adds indirection without benefit.
How does interface-based design map to hexagonal architecture?
The domain defines ports as interfaces — driven ports for what it needs, driving ports for what it offers. Adapters implement or call them: JPA and HTTP clients implement driven ports; controllers and listeners call driving ports. All dependencies point inward, so the domain is independent of frameworks and infrastructure.
How would you migrate a tightly coupled service with new calls everywhere toward this design?
Add characterisation tests; identify external dependencies (database, providers); extract consumer-owned interfaces for them; move object creation into a composition root or DI configuration; switch classes to constructor injection one at a time; then add fakes and unit tests. Do it incrementally along the most-changed paths first.
How would you justify the cost of interface-based design to a delivery-focused team?
Tie it to outcomes: faster, more reliable tests (no environment needed), the ability to switch providers or add resilience without touching business code, safer parallel work between teams, and a path to extracting services later. Apply it at boundaries where change is likely, not everywhere, so the overhead is small and the benefit visible.
What does this program print?
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
public class ClockQuiz {
record Coupon(String code, Instant expires) {
boolean valid(Clock clock) {
return clock.instant().isBefore(expires);
}
}
public static void main(String[] args) {
Instant noon = Instant.parse("2026-03-01T12:00:00Z");
Coupon coupon = new Coupon("SPRING", noon);
Clock before = Clock.fixed(noon.minusSeconds(1), ZoneOffset.UTC);
Clock atNoon = Clock.fixed(noon, ZoneOffset.UTC);
Clock later = Clock.offset(atNoon, Duration.ofHours(-2));
System.out.println(coupon.valid(before) + " "
+ coupon.valid(atNoon) + " " + coupon.valid(later));
}
}It prints true false true. Coupon asks an injected Clock for the time instead of calling Instant.now(), so the test controls the time. One second before noon the coupon is valid; at exactly noon isBefore is false, so it has expired. Clock.offset with minus two hours gives 10:00, so the coupon is valid again; the trap is reading the offset as "later". java.time.Clock is the JDK's own example of interface-based design: production code uses Clock.systemUTC(), tests use fixed clocks.
How does Spring decide which implementation to inject into a constructor parameter, and what happens when there are none or two?
It looks for beans whose type is assignable to the parameter type. With exactly one candidate it injects it. With none, startup fails with NoSuchBeanDefinitionException (unless the parameter is an Optional or an ObjectProvider); with several, it tries a @Primary bean, then a @Qualifier or a matching parameter name, and otherwise fails with NoUniqueBeanDefinitionException. A List<PaymentGateway> parameter receives all candidates, which is a simple way to build plug-in style designs.
All unit tests pass with an in-memory repository, but in production an order updated twice shows its first version. How do you find and prevent such bugs?
The fake and the real adapter disagree on the contract: here the JDBC adapter inserts a new row on save instead of updating, and a query returns the oldest row. Reproduce it with the adapter against a real database, fix the save as an insert-or-update, and write the expected behaviour down as a contract test that runs against the fake and the adapter (Example 5). From then on, a fake that diverges from production fails the build instead of hiding a bug.
Twelve services must move from one payment provider to another within a quarter, without a big-bang release. How does interface-based design shape the plan?
Make every service depend on one domain-owned PaymentGateway port, if it does not already, and put the provider SDK only in adapters. Build and contract-test the new provider's adapter once, as a shared library. Then switch service by service behind a configuration flag in the composition root, starting with low-volume services, and use a routing adapter that sends a share of traffic to the new provider while metrics compare both. Retire the old adapter when the last service has moved; the business code is never edited.
Test your knowledge on this topic →Flashcards from this topic's 15 questions, filtered by level and type.
Key Takeaways
- Depend on contracts, receive implementations from outside, wire in one place.
- DIP: business policy owns the interfaces; infrastructure implements them.
- Injection is the technique; IoC containers automate it.
- Interfaces at boundaries enable fakes, fast tests and replaceable infrastructure.
- The same structure scales from classes to ports-and-adapters to service APIs.