All lessons in Software Engineering: Programs, Systems, and Maintainable Software

Design Patterns with a Concrete Reason

Apply strategy and adapter where a measured variation justifies them.

35 minutes · Free lesson

What you will learn

  • Recognize a concrete variation that can justify a design pattern.
  • Use strategy and adapter without weakening a caller's behavioral contract.
  • Identify unnecessary abstraction and hidden global state.

A library has one due-date rule. Adding a factory, registry, and hierarchy of policy classes would create more machinery than the problem currently needs. Later, several member categories may require independently changing loan policies. The design pressure has changed, and a small strategy boundary may become useful.

Patterns name recurring arrangements of responsibilities. They are vocabulary for explaining a design, not requirements to add classes whenever a familiar name appears.

Find the reason for variation

A strategy encapsulates a replaceable way of performing a decision or calculation. For loan duration, a policy can accept the member category and borrowed date and return a due date under a clear contract. The lending service can use that policy without knowing every calculation detail.

The important property is substitutability at the stated boundary. Every accepted policy must return a valid date or a defined rejection and must respect the service's assumptions. A policy that mutates the database or closes the caller's connection violates a boundary intended for a pure calculation.

A simple function can be a strategy. An interface and multiple classes may be useful when implementations have coherent state or lifecycle needs. Choose the smallest form that expresses the actual variation.

Adapt an external shape to an internal contract

An adapter translates one interface into another. Suppose an imported catalog describes a copy using catalog_code and work_name while the domain expects stable copy and title identifiers. An adapter can parse and map the external representation before it reaches domain operations.

Translation is not permission to invent missing meaning. If two external records share a code unexpectedly, the adapter should surface the conflict rather than silently choose one. If the source does not distinguish a title from a physical copy, the import needs an explicit mapping decision.

Keep external vocabulary at the boundary where possible. When every domain function knows the external field names and error formats, changing the source format becomes a cross-system edit rather than an adapter change.

Worked example

Introduce a policy only when needed

  1. The initial product applies the same fourteen-day duration to every accepted member. A small pure function is sufficient.
  2. A new requirement gives research members twenty-one days and ordinary members fourteen days, with a specified unknown-category rejection.
  3. Define a policy contract returning a due date from member category and borrowed date. Keep database writes in the lending operation.
  4. Test each policy with fixed dates and verify the common requirements, including no due date before borrowing.
  5. If policies later come from different modules, substitute them through that boundary. Do not require the service to inspect implementation types and reimplement their rules.

Favor composition when behavior can vary independently

Inheritance can express a valid subtype relationship, but inheriting implementation is not automatically a good way to share a few lines. A subclass that refuses operations promised by its parent can break callers that rely on the parent contract.

Composition assembles behavior from collaborators. A lending service can contain a policy and a repository without pretending to be either one. This often makes independent variation clearer, though too many tiny collaborators can make the execution path hard to follow.

Test the boundary with observable behavior. A replacement repository should preserve the same result and conflict semantics for its supported use. A fake that accepts invalid data is not behaviorally interchangeable for a test of integrity, even if it has methods with the same names.

Watch for global lifetime disguised as convenience

A singleton-like global service can make access convenient but can also hide dependencies, retain state across tests, and complicate resource cleanup. Before introducing one, ask who owns its configuration and lifetime and how independent test instances will be created.

A module constant containing immutable configuration is different from a mutable global connection shared by unrelated operations. Describe the state and lifetime rather than treating every single-instance object as equally harmless or equally wrong.

The same caution applies to factories. A factory is useful when construction has meaningful variation or coordination. A wrapper that only renames a constructor may add little value unless it creates a useful future boundary already justified by the task.

Exercise

A due-date strategy writes a loan to the database and then returns the computed date. Why does this violate a useful strategy contract in the lending design?

Check your answer

The policy boundary is intended to calculate or reject a date from explicit inputs. Writing a loan introduces a hidden side effect, bypasses the service's transaction ownership, and can create partial state before other validation completes. Keep the write in the command's persistence boundary.

Exercise

An adapter silently maps an unknown external member category to ordinary membership. What question must be settled before this behavior is accepted?

Check your answer

The product must explicitly define whether unknown categories may receive that fallback. Otherwise the adapter invents eligibility or policy meaning and can accept an invalid command. A defined rejection with the original category retained for diagnosis is safer when no fallback rule exists.

Summary

Use patterns to explain concrete variation, translation, and responsibility. A small function may be enough for a strategy, and an adapter must preserve meaning. Evaluate substitutability, side effects, and lifetime instead of adding a pattern for its name.

Next action

Identify one real variation in your capstone and sketch both a direct implementation and a small pattern-based alternative. Choose one and explain the maintenance benefit that justifies its complexity.

Choose another lesson