Learning pathsPricingChecking sign-in…
Foundations

SOLID and composition

Design for a concrete change that is likely to happen.

Explore the design exercises →

SOLID describes ways to control change and preserve contracts. Apply each principle to a concrete requirement, then compare the extra indirection with the expected change. Composition lets a domain owner delegate one policy while keeping its own invariant intact.

Learning goals

  • Explain every SOLID principle with a practical counterexample.
  • Separate business policy from transport/storage mechanics.
  • Use narrow interfaces and explicit construction without weakening domain invariants.

What, when, why and how

Single Responsibility Principle

what
A component has one cohesive reason to change, judged by the policy or stakeholder that drives its behavior.
when
Pricing rules, payment transport and receipt formatting change independently.
why
Combining them makes a provider change risk pricing correctness.
how
Keep Checkout responsible for orchestration invariants, PricingPolicy for computing a quote and PaymentGateway for provider translation. A method count is not a responsibility count.

Worked example: Receipt layout changes should not touch the code enforcing all-or-nothing inventory ownership.

Common mistake: Splitting every method into a new class scatters one invariant across many owners.

Open/Closed Principle

what
A stable contract allows a known variation without modifying each consumer.
when
A second real pricing rule/provider/channel appears.
why
Repeated conditionals across callers make each new variant a coordinated edit.
how
Inject a pricing strategy whose output is a validated Money/Quote. Keep the caller responsible for currency, nonnegative amount and version constraints.

Worked example: FlatFee and DurationPricing implement one quote contract. Adding a rule should not require changing parking allocation.

Common mistake: Do not create an extension point for every imaginable future variation; a small explicit switch may be clearer for a closed domain.

Liskov Substitution Principle

what
Every implementation preserves the promised preconditions, postconditions and observable failures.
when
Replacing one gateway/storage/policy implementation with another.
why
Matching method names is not behavioral compatibility.
how
Specify timeout/unknown semantics, ordering, nullability, thread safety and idempotency in the interface contract. Contract-test every implementation.

Worked example: An adapter that returns FAILED for a network timeout cannot substitute for a gateway promising FAILED means definitely no charge.

Common mistake: Inheritance that tightens input rules or silently weakens output guarantees breaks callers even if Java accepts the override.

Interface Segregation Principle

what
Clients depend on the capabilities they actually need.
when
A reporting reader should not acquire money-movement or administrative methods.
why
Large interfaces leak authority and force fakes/adapters to implement irrelevant operations.
how
Split BalanceReader from TransferWriter when clients/permissions vary. Keep coupled operations together when splitting would let callers violate one transaction.

Worked example: A catalog reader sees product descriptions; inventory reservation requires a separate command contract.

Common mistake: Splitting debit and credit into independent writer interfaces can destroy a balanced transfer invariant.

Dependency Inversion and injection

what
High-level rules depend on contracts; adapters implement transport/storage details. Injection supplies those dependencies explicitly.
when
A domain flow needs a payment provider, clock or repository.
why
Hardcoded network clients and wall clocks make failure testing and replacement difficult.
how
Constructor-inject a narrow Gateway and Clock. Keep DTO mapping and provider status translation in adapters. Resolve implementations at the composition root; a DI framework is optional.

Worked example: Notification retry tests advance a trusted fake clock and use a provider that returns UNKNOWN without actually sending messages.

Common mistake: A generic Repository<T> often hides required transactions, conditional writes and uniqueness instead of expressing them.

Composition versus inheritance

what
Composition delegates behavior to contained collaborators; inheritance promises an is-a contract.
when
Algorithms/configuration vary independently from entity identity.
why
Subclass combinations multiply rapidly, and base class changes leak into all variants.
how
Prefer a Checkout that has a PricingPolicy/Gateway over subclasses for every provider×discount combination. Use inheritance only where substitution and shared behavior remain clear.

Worked example: Logging decorators can add metrics to a sink while preserving its delivery contract.

Common mistake: Composition is not permission to stack wrappers that retry unknown financial effects; side-effect semantics still govern.

Contract ownership at the boundary

what
An interface should express the operation the domain needs, including retry and evidence semantics.
when
A provider has a much larger API than the use case.
why
Leaking raw provider statuses forces every caller to reinterpret safety.
how
Return a typed result with stable operation ID and known-success/known-no-effect/unknown classification. Validate metadata and keep secrets/provider DTOs inside the adapter.

Worked example: Provider HTTP 202 means accepted request, not delivered email. Preserve that distinction in the domain result.

Common mistake: A fake always returning success proves call wiring, not substitutability under real partial failures.

A narrow gateway contract and explicit composition

Illustrative Java 21 snippet; the linked exercises contain complete executable references and tests.

Solution.java Java 21
enum ChargeStatus { SUCCEEDED, DEFINITELY_FAILED, UNKNOWN }
record ChargeResult(String operationId, ChargeStatus status) {}
interface ChargeGateway {
    // Retry the same key with the same request; UNKNOWN requires reconciliation.
    ChargeResult charge(String key, long minorUnits, String currency);
}
final class ChargeService {
    private final ChargeGateway gateway;
    ChargeService(ChargeGateway gateway) {
        this.gateway = java.util.Objects.requireNonNull(gateway);
    }
    ChargeResult request(String key, long amount, String currency) {
        if (key == null || key.isBlank() || amount <= 0
            || currency == null || currency.isBlank())
            throw new IllegalArgumentException("charge request");
        return gateway.charge(key, amount, currency);
    }
}

The service knows an explicit domain contract, while the adapter translates provider facts. This illustrative snippet does not implement durable deduplication, authorization, reconciliation or exception translation. Its interface requires those semantics to be supplied honestly by the adapter and coordinating state owner; injection alone cannot provide them.

Worked design exercise

Refactor one notifier that hardcodes email, SMS, template rendering and retries.

  1. List actual change drivers: message content, recipient permission, channel transport and delivery state.
  2. Keep one delivery owner responsible for retry identity and state precedence.
  3. Inject strict renderer and channel adapter contracts rather than subclassing every combination.
  4. Define accepted/delivered/unknown results and a stable logical send key.
  5. Test each adapter against the same failure contract, including response loss.
Compare your reasoning with the worked answer

Rendering and transport can vary through composition while delivery invariants stay in one owner. A new channel adds an adapter/policy configuration. Provider failover on unknown delivery remains an explicit reconciliation decision.

Engineer to Staff follow-ups

Engineer: Does dependency injection require a framework?

No. A constructor receiving an interface is sufficient; the composition root chooses an implementation.

Senior: How do you detect an LSP violation in a gateway?

Write contract tests for definite failure, unknown timeout, duplicate identity and contradictory outcomes. A replacement must preserve those meanings.

Staff: How do interfaces evolve without breaking deployed clients?

Version changed semantics, preserve compatibility where promised, run old/new contract fixtures and plan adapter rollout. Adding a method is not enough when acknowledgement meaning changes.

Apply it in design exercises

For each exercise, derive the object owner, schema keys/relationships and transaction boundary before revealing the reference.

Your study notes