Foundations 0/8

Lesson 8 of 8

Design principles

Use changes to a checkout system to understand class responsibilities, dependencies and unnecessary abstraction.

1,485 words · 7 min read Useful background: Objects and classes

A responsibility is a reason for code to change

Design principles help divide a program into responsibilities that can be understood and changed separately. A responsibility is a policy the code owns, such as calculating a price or translating a payment provider’s response. When unrelated policies share one module, a change to either requires understanding the other and reviewing its callers.

Cohesion describes how closely a module’s operations belong to one responsibility. Coupling describes the dependencies between modules, including the data formats and behavior each expects from another. A useful boundary keeps related decisions together and makes the remaining dependency explicit. Method count and file length provide little evidence on their own: a large class can own one policy, while a short function can entangle several.

An interface states the capability a caller needs without spreading implementation details through that caller. Checkout may need to request a charge and receive an accepted payment identifier. The payment adapter can translate that request into a provider-specific SDK call. A provider response rename then belongs in the adapter, provided the interface’s meaning stays unchanged.

Every boundary adds some cost. Someone must name the contract, construct the collaborators and test their integration. An interface is justified when it isolates a concrete source of change or expresses a useful testing boundary. A separate abstraction for each class can increase the amount of code a reader must follow without reducing the changes that reach it.

Translate the names into checks you can perform

SOLID collects five principles about class responsibilities and dependencies. DRY, KISS and YAGNI are three shorter rules about duplication and scope. Each name is useful only as a question you can ask of real code, so the table pairs each one with a check on a checkout design and the failure it prevents.

Questions to ask while reviewing a checkout design
PrincipleConcrete checkFailure to look for
Single responsibility principleCan a receipt wording change avoid payment parsing code?One module owns unrelated policies.
Open/closed principleCan a second payment implementation satisfy the existing contract without editing checkout?Every provider addition edits a growing conditional.
Liskov substitution principleDo all implementations preserve the same success and failure promises?A replacement reports success before payment is accepted.
Interface segregation principleDoes checkout depend only on operations it uses?A fake payment object must implement reporting and refunds.
Dependency inversion principleDoes checkout name a payment contract, with provider details outside it?Provider SDK types appear throughout business logic.
DRY: don’t repeat yourselfIs each business rule, such as the tax rate, defined in one authoritative place?The tax rate changes in checkout but not in the invoice generator.
KISS: keep it simpleIs this the simplest design that meets the stated requirements?A plugin registry and configuration file exist for one payment provider.
YAGNI: you aren’t gonna need itDoes each abstraction serve a requirement that exists today?Multi-currency support is built, tested and maintained for a shop that sells in one currency.

These checks overlap. A narrow payment contract reduces the number of provider details in checkout, and it also makes a replacement easier to test. DRY concerns knowledge rather than text: two functions with identical arithmetic that encode different business rules should stay separate, because they will change for different reasons. A contract that hides information the caller needs, such as whether retrying can charge twice, creates a different problem.

Separate payment translation from checkout policy

Suppose a web handler and a background worker both call checkout. Its first implementation calculates a total, calls a provider SDK, interprets the response and formats a receipt in one module. A provider response change now requires editing checkout even though the purchase policy is unchanged. A receipt wording change also touches that module, enlarging the code that must be reviewed and tested for either change.

Separate the provider translation into an adapter that implements a narrow payment interface. Checkout continues to calculate the purchase total and calls that interface to request a charge. A receipt component formats the accepted result. The application’s entry point constructs these concrete collaborators and supplies them to checkout. This arrangement is dependency injection: the caller receives the dependency it uses instead of constructing it.

Dependency inversion concerns which contract the business logic depends on. Checkout defines the payment capability it needs; the provider adapter conforms to that contract. If checkout instead returns provider SDK objects to its callers, response details still spread through the application despite the extra adapter class. Translate those details before returning a domain result.

The boundary isolates changes only while its behavioral promises hold. Replacing an accepted payment id with a pending request id changes when checkout may mark an order paid. Every implementation and caller must then be reviewed, even if both results are represented as strings. Substitutability requires the same meaning of success, amount units and retry behavior; a matching method signature covers only part of that contract.

Follow a change through the import graph

Which modules need review when the provider’s response format changes, when receipt wording changes and when the payment contract itself changes? Compare the combined checkout with the separated design.

Web handlerReview consumer
Background workerReview consumer
CheckoutDirect edit
  • Web handler → Checkout
  • Background worker → Checkout

3 modules in the static review set.

Arrows show static imports. Provider changes still need integration tests through checkout.

With separate boundaries, a provider change stops at the adapter, but a change to the payment contract still reaches the port, the adapter and every client of checkout. The isolated design contains more modules; that extra wiring pays for itself when provider and receipt changes occur independently. For a small script with one stable dependency, a function parameter gives the same boundary without a class hierarchy.

Inject the capability the caller needs

In Python, a Protocol describes the operations an object must provide. Checkout receives an object with a charge method; it does not construct a provider client. The fake below records calls, so a unit test can inspect the amount without making a network request.

class Payments(Protocol):    def charge(self, cents: int, key: str) -> str: ...@dataclassclass FakePayments:    calls: list[tuple[int, str]]    def charge(self, cents: int, key: str) -> str:        self.calls.append((cents, key))        return "payment-1"def checkout(items: list[int], key: str,             payments: Payments) -> str:    if not items or any(cents <= 0 for cents in items):        raise ValueError("positive item prices required")    return payments.charge(sum(items), key)fake = FakePayments([])assert checkout([300, 200], "order-7", fake) == "payment-1"assert fake.calls == [(500, "order-7")]
Python: a narrow payment port and a recording fake

The caller supplies a stable operation key. A real adapter must translate provider failures and implement the agreed retry behavior. The fake proves which call checkout makes; it proves neither provider compatibility nor payment durability. Python type hints also need a type checker to reject incompatible implementations before runtime; Java or C# would declare an interface that the compiler checks.

Substitution includes behavior beyond the method signature. Document the amount unit, which failures can be retried and what the returned id means. A payment provider that rounds cents differently violates the contract even if its class satisfies the protocol.

What stays true

Every payment implementation must preserve the port’s amount units, retry behavior and meaning of success.

Checkout then computes the same total and makes the same logical charge request regardless of the injected implementation. Contract tests check each adapter against those promises; integration tests cover wiring and provider translation. An unchanged signature alone cannot establish substitutability.

Pay for a boundary where changes justify it

What each structural choice costs and when it pays off
DecisionCostWhen it pays off
A provider adapterMore wiring and contract testsProvider changes are expected, or tests need a fake provider.
Dependency injection at the entry pointOne place must construct and connect every collaboratorCollaborators differ between production, tests and environments.
A broad shared interfaceMore consumers per contract changeRarely: unrelated callers must implement or review operations they never use.
An abstraction before a second useIndirection every reader must followOnly when the variation is already a stated requirement.

Boundaries that fail under a real change

  1. Return provider SDK objects from the payment port.

    Where it breaks
    A provider rename from transaction_id to payment_id forces checkout and both callers to change.
    The fix
    Translate the response inside the adapter and return the domain value promised by the port.
  2. Treat matching methods as matching behavior.

    Where it breaks
    The replacement returns a request id while checkout records the order as paid.
    The fix
    Specify accepted versus pending outcomes and test each implementation against them.
  3. Extract a general framework before a second use exists.

    Where it breaks
    A single receipt formatter gains factories, registries and configuration that callers must understand.
    The fix
    Keep the direct function until a concrete variation needs a separate boundary.
  4. Share code because two policies happen to use the same arithmetic today.

    Where it breaks
    A refund rule changes while the original tax calculation must remain unchanged.
    The fix
    Share stable domain meaning; allow independent policies to evolve separately.

Test the boundary in a larger system

Related topics

Further reading