A practical study book about objects, contracts, composition, and a complete circulation-desk project
Learn to design understandable object models, protect invariants, choose composition or inheritance, isolate dependencies, and test behavior using runnable Python examples.
15 chapters7 diagrams30 practice tasks
Clear explanations. Worked examples. Practice with reasoning. Original text · CC BY-SA 4.0 Code · MIT
Before you begin
How to use this guide
Learners who know variables, functions, and basic collections, plus developers who want clearer design judgment beyond class syntax.
Helpful background
Basic Python functions, exceptions, lists, and dictionaries
Python 3.11 or newer for runnable examples
No prior design-pattern vocabulary required
What you will be able to do
Distinguish entity identity from value equality
Protect invariants with clear commands and failure guarantees
Choose composition, protocols, and inheritance for explicit reasons
Build test seams without a dependency-injection framework
Implement and test a scoped circulation model
A useful study rhythm
Read the explanation, close the book, and draw or explain the idea from memory. Predict each example before running or tracing it. Attempt the chapter exercises, compare your reasoning with the solution manual, and return to the source when an assumption changes.
For a first pass, follow the chapter order. For revision, use the contents and glossary. Assessment answers and exercise solutions are separated from the questions so you can retrieve an answer before seeing it. Internal links and bookmarks work in most PDF readers; the printed page number helps when reading on paper.
Scope and assumptions
Runnable examples use Python 3.11+ standard-library features. Cross-language notes describe Java/C++ distinctions but do not present them as interchangeable language mechanics.
The capstone is single-process and in-memory. Database concurrency, authentication, distributed transactions, and delivery guarantees are extension topics rather than hidden promises.
This book teaches design reasoning and a substantial foundational workflow; it does not claim that every design pattern is appropriate or covered.
Original explanations and diagrams are CC BY-SA 4.0; original code is MIT. Linked external references retain their own terms.
Core explanations and original diagrams are available offline. External books, videos, and documentation remain at their publishers’ sites and may require an internet connection or a separate account.
Chapter 01
Start with a model, not a class diagram
Choose what the program needs to represent before choosing syntax.
By the end of this chapter
Distinguish domain behavior from a list of nouns
Explain when a function or record is enough
Model one useful slice of the world
Object-oriented programming groups state and behavior behind interfaces that other code can use. The useful question is not how many classes a program has. It is whether a reader can understand which objects are responsible for which rules, and whether those rules remain true as the program changes. A design with three clear objects can be stronger than a diagram containing thirty vague ones.
A model is intentionally incomplete. A library circulation program needs to know whether a particular copy is available, but it may not need the book cover's exact color or the shelf's manufacturing date. Begin with a concrete use case: a member checks out an available copy. Write the inputs, successful outcome, and failure cases. That gives you behavior to design instead of an unlimited collection of possible real-world details.
Not every noun deserves a class with behavior. A title string can remain a string. A conversion can remain a function. A group of independently meaningful fields can be a record. Introduce an object boundary when it protects a rule, coordinates a lifecycle, or gives callers a useful stable way to request behavior. OOP is a tool for managing relationships, not a requirement to turn every line into a method.
A function is enough for an independent calculation Python 3.11+
def total_pages(page_counts):
page_counts = tuple(page_counts)
if any(count < 0 for count in page_counts):
raise ValueError("negative page count")
return sum(page_counts)
print(total_pages([120, 80, 200]))
A domain vocabulary becomes useful when it includes actions and rules. Book is a noun; loan, return, and reserve may be actions or records depending on the use case. A single catalog title may have many physical copies, so a title and a borrowable copy should not be confused. If availability belongs to a copy, storing it on a shared title record will produce the wrong behavior as soon as two copies exist.
Use small scenarios to challenge the model. What if a member borrows two different copies of the same title? What if a returned copy has an outstanding reservation? What if a checkout request is repeated? You do not need to implement every feature immediately, but identifying the boundary of today's model prevents accidental promises about tomorrow's features.
A good first design can be a few data values and functions with explicit inputs. When several operations must preserve the same state rule, an object boundary may make that coordination clearer. Evaluate the design by how safely it expresses the required changes and how easily it can be tested, rather than by whether it matches a fashionable diagram.
An object has an identity, a type, and a value or state. Two names may refer to the same object. If the object is mutable, a change made through one name can be visible through another. This is aliasing. In Python, assignment binds a name to an object; it does not automatically clone the object's state into a separate independent instance.
Equality asks whether two objects should count as equal according to their type's comparison behavior. Identity asks whether they are the very same object. Use equality for ordinary value comparisons. Identity checks are useful for special singleton markers such as None or when the model explicitly cares about one particular object. Do not use observed identity of small integers or interned strings as an application contract.
Draw a simple arrow from each name to the object it reaches. Then trace mutations on the object, not on the arrow. Reassigning a name changes that one binding; appending to a shared list changes the shared list. This distinction explains many beginner bugs in caches, default arguments, and nested data structures.
Aliasing and a shallow copy Python 3.11+
first = {"tags": ["python"]}
second = first
third = first.copy()
second["tags"].append("oop")
print(first is second)
print(first is third)
print(third["tags"])
Expected result
True
False
['python', 'oop']
A shallow copy does not clone nested objects. The first and second names share one dictionary. The third name reaches a different dictionary, but both dictionaries still reach the same nested tag list.Scroll horizontally to read the full diagram on a small screen.
A shallow copy creates a new outer container and copies its references. That is often exactly what you want for immutable elements, but it does not create deep independence for nested mutable objects. A deep copy recursively copies supported contents, yet even that is not a universal domain operation. A copied database connection or identity-bearing entity may not make sense at all.
Decide which objects are entities and which are values. A library copy with an assigned identifier remains the same entity while its status changes. A duration of thirty minutes is a value that can be replaced by an equal duration without changing identity-sensitive behavior. The distinction helps determine equality, copying, caching, and persistence rules.
Reduce unnecessary sharing when it makes reasoning difficult. Return an immutable view or a copy when callers should not mutate internal collections. When sharing is intentional, document who may change the state and at what boundaries. Encapsulation becomes much easier when the ownership and aliasing story is explicit.
Give callers safe operations instead of unrestricted field edits.
By the end of this chapter
Define and preserve an invariant
Avoid leaking mutable internal representation
Private-looking names do not replace a contract
An invariant is a statement that should hold whenever a public operation has successfully completed. A reading budget may never be negative. A checkout collection may contain each copy identifier at most once. Write that statement before selecting private fields or adding property methods. Without a rule to preserve, hiding fields can become ceremony without a clear benefit.
Python uses naming conventions rather than Java-style mandatory private access for ordinary attributes. A leading underscore marks an implementation detail for cooperative callers. Name mangling with two leading underscores solves a different accidental-name-collision problem; it is not a security boundary. Other languages enforce different access controls, but no access modifier repairs a logically incorrect public operation.
Prefer commands that express the intended change. spend(minutes) can validate a nonnegative amount and prevent overspending. A generic set_remaining method forces callers to reconstruct the rules and can allow transitions that should never occur. A useful interface narrows the number of ways the object can become invalid.
Guard the state transition, not only the initial value Python 3.11+
Representation leaks can bypass an otherwise careful interface
Suppose an object stores a list of current loans and returns that exact list from a property. A caller can remove an entry directly, bypassing return validation, audit events, or related state updates. Even if the attribute itself has no setter, the returned list can still be mutable. Read-only access to a reference is not the same as an immutable result.
Return a tuple snapshot when callers only need to inspect identifiers, or return carefully chosen value objects. If the collection contains mutable entities, a tuple prevents changing the collection structure but does not freeze those entities. Document the depth of the protection. Otherwise a shallow read-only wrapper can create a false sense of safety.
A boundary should also state its failure guarantee. If spend raises because the amount is too large, the remaining budget should be unchanged. Check the conditions before mutation, then apply the change once. A test should verify both the error and the object's state afterward. This pattern scales from a small class to a transaction that coordinates several records.
Establish valid state without surprising side effects.
By the end of this chapter
Construct valid objects or fail clearly
Separate resource acquisition and domain setup
A constructor establishes the starting promise
A constructor gives an object its initial state. After successful construction, callers should know which operations are valid. Requiring every caller to remember a separate initialize method creates a period in which the object exists but is not ready. If such a lifecycle is necessary, represent the states explicitly instead of relying on an undocumented sequence of calls.
Validate essential inputs before storing a state that other methods assume to be valid. A positive capacity, nonempty identifier, or supported currency is part of the domain contract. Avoid silently repairing invalid values unless normalization is explicitly intended. Converting a misspelled currency to a default currency may produce a plausible but incorrect financial result.
Keep unpredictable external work out of ordinary domain constructors where possible. A constructor that sends an email, opens a remote connection, or reads a changing clock makes object creation difficult to test and retry. A separate orchestration boundary can acquire the external result and pass a validated value or collaborator into the domain object.
A constructor establishes one explicit valid state Python 3.11+
class Shelf:
def __init__(self, capacity):
if not isinstance(capacity, int) or isinstance(capacity, bool):
raise TypeError("capacity must be an integer")
if capacity < 1:
raise ValueError("capacity must be positive")
self._capacity = capacity
self._titles = []
def add(self, title):
if len(self._titles) >= self._capacity:
raise ValueError("shelf is full")
self._titles.append(title)
def titles(self):
return tuple(self._titles)
shelf = Shelf(2)
shelf.add("Networks")
print(shelf.titles())
A domain object such as Money is usually a value with no external resource to close. A file, database session, or lock has an acquisition and release lifecycle. In Python, a context manager expresses work that should be followed by cleanup, even when an exception leaves the block. This is different from hoping that a finalizer happens to run at a convenient time.
Do not use object destruction timing as a business event. A loan is not returned because the last Python reference to a Loan object disappears. Returning a physical copy is an explicit domain command that must be recorded. Memory lifetime, resource lifetime, and business lifecycle can overlap, but they are not interchangeable concepts.
When an object has several legitimate states, make the allowed transitions part of its interface. Construction might create a draft reservation, confirm might establish a confirmed reservation, and cancel might move it to a terminal state. A caller should receive a clear result when a transition is not allowed. Testing sequences then becomes as important as testing individual methods.
Keep hash keys stable and validate shallow immutability
A value is defined by meaning, not by its address
A value object represents a meaningful quantity or description, such as a duration, date range, or amount in one currency. If two values have the same relevant components, substituting one for the other should not change the calculation. Entity objects instead often carry stable identity even when their descriptive fields change. Choose the equality policy that matches the domain.
A small immutable data class can be an effective value representation in Python. frozen=True prevents ordinary attribute reassignment through the generated interface, but it does not deeply freeze mutable members. A frozen object containing a list can still expose a mutable list. Use immutable components when stable value behavior is required.
An amount should include its unit. Two hundred cents and two hundred rupees are not equal quantities merely because both contain the integer 200. Addition should reject incompatible currencies or require an explicit conversion step. Good types eliminate ambiguous combinations before those combinations become accounting errors.
An immutable amount with an explicit unit Python 3.11+
from dataclasses import dataclass
@dataclass(frozen=True)
class Money:
cents: int
currency: str
def add(self, other):
if self.currency != other.currency:
raise ValueError("currency mismatch")
return Money(self.cents + other.cents, self.currency)
first = Money(250, "USD")
second = Money(250, "USD")
print(first == second)
print(first.add(second))
A hash-based collection uses a hash value to find candidate keys and equality to decide whether a key matches. Objects that compare equal must have equal hash values. If fields used for hashing change after insertion, a collection may no longer find the object where it expects. This is why mutable identity-bearing objects usually make poor keys when equality depends on changing fields.
Do not treat a data class as automatic domain validation. Generated initialization and comparison methods save boilerplate, but your rules still need implementation. The small Money example assumes integer cents and a previously validated currency string. A production value type should define accepted currencies, integer validation, rounding at boundaries, overflow concerns in other languages, and display rules.
When a value changes, returning a new value can make reasoning easier than mutating a shared one. A price calculation can produce a new Money result while the original remains unchanged. This supports tests and safe sharing, but it may allocate additional objects. Measure actual performance concerns before giving up a clear value model for an optimization you have not demonstrated.
Build behavior by connecting focused collaborators.
By the end of this chapter
Distinguish has-a relationships from is-a promises
Delegate one responsibility without hiding ownership
Use collaborators when responsibilities vary independently
Composition means that an object uses other objects to perform parts of its work. A reading report can use a formatter and a delivery service without being a kind of formatter or a kind of email. The relationships are has-a or uses-a relationships. This keeps separate reasons for change from being forced into one inheritance hierarchy.
Delegation is the act of forwarding a responsibility to a collaborator. A coordinator can validate a request, ask a policy for a decision, and ask a repository to store the result. It should not merely forward every method of a large object under a new name. The boundary is useful when it expresses a smaller contract, adds a real policy, or isolates a dependency.
Composition does not mean sharing is automatically safe. Decide who creates the collaborator, who owns its resource lifecycle, and whether it can be reused concurrently. A formatter with no mutable state is easier to share than a formatter that stores the current customer and the last generated result in instance fields.
A report uses a formatter rather than inheriting from it Python 3.11+
A coordinator delegates one concern. Report owns the reporting workflow and uses a formatter through a narrow operation. It does not inherit formatter identity or unrelated methods.Scroll horizontally to read the full diagram on a small screen.
Choose composition for a reason, not as another slogan
Inheritance can be appropriate for a stable behavioral family, so prefer composition is a heuristic rather than a prohibition. Ask whether a subtype can honestly fulfill every relevant promise of the parent interface. If the relationship is simply reuse this helper implementation, a composed helper often states that intent more accurately.
A decorator is one useful composition pattern: it presents the same small interface while adding behavior around a collaborator, such as timing, caching, or logging. The added behavior must preserve the original contract. A cache that returns stale authorization decisions or logs secret arguments may violate the contract even though its method signatures match perfectly.
Do not introduce a separate class for every one-line operation. In Python, a function can be a suitable collaborator when only one operation varies. A small interface should make the design easier to explain and test, not require readers to jump through ten empty layers to find the real calculation. Start from the concrete variation the program actually needs.
Let different implementations support the same useful behavior.
By the end of this chapter
Explain dynamic dispatch without requiring inheritance
Separate interface compatibility from semantic compatibility
Callers depend on promised behavior
Polymorphism lets one caller use different implementations through a common contract. A lesson renderer may write to a terminal sink, a file sink, or an in-memory sink used by tests. The caller needs the write operation and its behavior; it should not need a chain of type checks for every possible implementation.
Python supports structural use: an object can be passed to code that calls methods it provides, without inheriting from a particular base class. A typing.Protocol can document this structure for static tools. Type annotations do not, by themselves, enforce every runtime input rule. A runtime-checkable protocol also does not prove that an implementation preserves the intended meaning of its methods.
A contract includes more than a name and parameter count. Does write append or replace? Is it allowed to fail? Does success mean buffered locally or durably stored? Does it mutate the passed value? Two objects can share a method name and still violate each other's expectations. State the relevant behavioral promises before declaring them interchangeable.
Different implementations satisfy a narrow structural interface Python 3.11+
An interface with many unrelated operations forces implementations to support behavior they do not naturally provide. A read-only source should not need a delete operation that always raises not supported. Split interfaces around the needs of callers when those needs differ meaningfully. This is often called interface segregation, but the practical goal is a usable honest contract.
An abstract base class can express a deliberately named family and prevent instantiation until required abstract methods are implemented. A protocol can express structural expectations without requiring that inheritance relationship. Neither is automatically better. Use the form that communicates the relationship and fits the tools your project uses.
When implementations cross an external boundary, test the contract against the real adapter as well as a test double. An in-memory repository may preserve insertion order while the database adapter does not. If ordering is required, include it in the contract and verify it. Otherwise a test suite can accidentally teach the application to depend on properties only the fake implementation happens to provide.
Use a subtype only when callers can keep their expectations.
By the end of this chapter
Apply behavioral substitution to a concrete example
Avoid strengthening preconditions or weakening promises
A subtype inherits obligations
Inheritance can express that one type belongs to a behavioral family. If a caller accepts the parent interface, a subtype should not surprise the caller by requiring stricter inputs or delivering weaker outcomes than that interface promises. The principle is usually associated with Liskov and Wing's work on behavioral subtyping. Its practical purpose is reliable reasoning about callers that do not know the concrete subtype.
Suppose an account interface promises that withdraw accepts any nonnegative amount up to the current balance. A subtype that suddenly requires every withdrawal to be at least one hundred violates a caller's expectations. The subtype may have a reasonable real-world policy, but it is not a faithful implementation of that particular interface. Change the abstraction or model the policy as a collaborator rather than forcing the relationship.
The classic rectangle and square problem is another warning about mutable contracts. If a Rectangle interface permits setting width while keeping height unchanged, a Square subtype cannot maintain equal sides and preserve that setter promise simultaneously. The issue is not that squares are mathematically unrelated to rectangles. The problem is that the mutable programming interface exposes incompatible behavior.
A subtype must preserve caller assumptions. The caller knows the interface contract. Any selected implementation must accept the promised inputs and preserve its stated outcomes.Scroll horizontally to read the full diagram on a small screen.A small compatible family Python 3.11+
class Discount:
def apply(self, cents):
if cents < 0:
raise ValueError("negative price")
return cents
class TenPercentOff(Discount):
def apply(self, cents):
if cents < 0:
raise ValueError("negative price")
return cents - cents // 10
for policy in (Discount(), TenPercentOff()):
print(policy.apply(1000))
Use inheritance for a stable abstraction, not a shortcut
Implementation inheritance can create hidden coupling when a subclass depends on undocumented details of parent methods. A parent refactor can then break the subclass even when ordinary callers would not notice a change. Prefer a narrow documented extension point, or use composition when the goal is to reuse an algorithm while changing one policy.
A subclass should not need to neutralize inherited operations constantly. Repeated methods that raise not implemented for ordinary parent capabilities suggest that the parent interface groups incompatible responsibilities. Instead of forcing ReadOnlyRepository to inherit delete and save, define a read interface and a separate write interface when callers genuinely have different needs.
In C++, polymorphic deletion through a base pointer requires an appropriate virtual destructor on the base. In Java, method dispatch and final methods have their own rules. In Python, method resolution follows its documented resolution order. These language mechanisms differ, but the behavioral question remains the same: can callers continue relying on the abstraction's promises? Learn the mechanism and the contract together.
Specify what success and failure each leave behind.
By the end of this chapter
Validate before mutation
Distinguish in-memory atomicity from durable transactions
A method can fail after it has changed something
A method that performs several assignments can expose partial state if a later step fails. Imagine checkout removing a copy from availability before discovering that the member has reached a loan limit. The error message may be correct while the stored state is now wrong. A robust contract includes a failure guarantee, not only a successful return value.
For a small in-memory object, collect and validate all required facts first, then perform the state transition as one deliberate step. If several mutable objects must change together, define which component coordinates the invariant. Scattering one operation across unrelated setters makes it difficult to find the boundary where all relevant rules are checked.
This approach does not make external operations atomic automatically. Sending a message and updating a database can fail between the two actions. A memory rollback cannot unsend an email. When crossing a durable or distributed boundary, use the storage and delivery mechanisms appropriate to that boundary, and state what retries or reconciliation will do.
Validate both values before changing the balance Python 3.11+
An expected domain rejection, such as no available copy, differs from a programmer error, such as passing an object without a required operation. A network timeout differs again because the remote outcome may be unknown. Name and represent these categories so callers can decide whether to ask the user for another choice, retry safely, or alert a developer.
Do not catch Exception and turn every failure into success. That can conceal broken assumptions, corrupted data, or unexpected adapter failures. Catch a specific error at a boundary where you can add useful context or select a valid recovery path. Preserve the original cause when translating errors so operational diagnosis remains possible.
Tests should verify sequences around failure. Begin with a valid state, request a prohibited transition, confirm the rejection, then perform another valid transition. If the later valid operation fails unexpectedly, the earlier failure may have damaged the object. These tests reveal problems that isolated success-only examples often miss.
Pass collaborators where they are needed and keep policy visible.
By the end of this chapter
Use constructor injection without requiring a framework
Isolate time, storage, and network dependencies
Hidden dependencies make behavior harder to reproduce
A dependency is something a component needs in order to do its job. Some dependencies are obvious parameters. Others are hidden global variables, a system clock read in the middle of a calculation, or a database client created inside a method. Hidden dependencies make tests sensitive to environment and timing, and make reuse harder to reason about.
Dependency injection means supplying a required collaborator instead of letting the component locate or construct it invisibly. A constructor parameter is often enough. No container or framework is required. The caller wires the concrete application at its edge, while the core depends on a smaller useful contract.
Inject variation that matters. If a due-date calculation depends on today's date, accept a date value or a clock collaborator. If a policy needs a loan count, accept the relevant count or a narrow repository operation. Do not inject every local variable as a separate service. The goal is explicit dependencies and reproducible decisions, not maximal configuration.
A fixed clock makes a due-date example deterministic Python 3.11+
from datetime import date, timedelta
class LoanPolicy:
def __init__(self, today):
self._today = today
def due_date(self, days):
if days < 1:
raise ValueError("positive loan period required")
return self._today() + timedelta(days=days)
policy = LoanPolicy(lambda: date(2026, 12, 1))
print(policy.due_date(14))
Expected result
2026-12-15
Keep replaceable adapters at the edge. Application wiring supplies a real or test collaborator through a narrow interface. Domain rules remain independent from external setup details.Scroll horizontally to read the full diagram on a small screen.
A test seam is a boundary at which one implementation can be replaced with another for a test. A memory repository can make a use-case test fast and deterministic. A fixed clock can make an overdue calculation repeatable. These replacements are valuable when they obey the same relevant contract as production collaborators.
An in-memory fake may accidentally provide stronger properties than the real adapter. It may preserve order without an order clause, never time out, or return shared live objects where the real database returns reconstructed values. Write adapter contract tests for behaviors the application relies on. Unit tests of the core and integration tests of the adapter answer different questions.
Keep the direction of dependency clear. A domain policy should not import a database driver's connection type merely to count current loans. A narrow interface or already retrieved value can express what it needs. This makes a later storage change less likely to force edits throughout the model, while still allowing the application boundary to use concrete tools directly.
Use observable contracts to make refactoring safe.
By the end of this chapter
Choose meaningful examples and boundary checks
Avoid brittle tests of internal call sequences
A test is an executable claim about a contract
A useful unit test begins with a meaningful state, performs one operation, and checks an observable outcome. Arrange, act, assert is a helpful shape, but the value comes from the scenario. A test named test_method_1 says little; a name such as rejected_payment_preserves_balance explains the promise being protected.
Cover boundaries and failure paths deliberately. For a capacity-limited shelf, test adding below capacity, exactly reaching capacity, and rejecting one more item. Then confirm the contents remain unchanged after the rejection. Repeating an operation can expose hidden state that a single call misses. Equality, copying, and serialization often deserve their own examples.
Prefer assertions through the public interface when possible. A test that inspects a private list layout can fail after a harmless switch to a dictionary. If the representation detail is not part of the promised behavior, such a failure discourages safe refactoring. Public outcomes, invariants, and explicit adapter contracts form a more durable testing boundary.
A test verifies rejection and the remaining state Python 3.11+
import unittest
class Counter:
def __init__(self):
self._value = 0
@property
def value(self):
return self._value
def add(self, amount):
if amount < 0:
raise ValueError("negative increment")
self._value += amount
class CounterTests(unittest.TestCase):
def test_rejected_increment_keeps_value(self):
counter = Counter()
counter.add(3)
with self.assertRaises(ValueError):
counter.add(-1)
self.assertEqual(counter.value, 3)
if __name__ == "__main__":
unittest.main()
Expected result
One test passes; unittest reports OK on its diagnostic stream.
A stub supplies predefined answers. A fake implements a simplified working version, such as a memory repository. A mock can verify interactions, such as whether a notification boundary was called with a required event. The terms vary between tools, so explain the role rather than relying on the label alone.
Interaction checks are appropriate when the interaction itself is the contract, but over-specifying every internal call makes tests fragile. If a report returns the correct result, a harmless change from two helper calls to one should not break ten tests unless that call pattern was itself required. Verify externally meaningful effects and use the fewest interaction assumptions needed.
A broad test suite is still not a proof of every possible behavior. Keep tests focused on risks and documented examples, use type checking and code review where useful, and test real boundaries separately. When a bug is found, reduce it to a small failing example and retain the example as a regression check. That turns a misunderstanding into lasting project knowledge.
Replace scattered flags with named transitions when the lifecycle demands it.
By the end of this chapter
Model allowed transitions explicitly
Test invalid transitions and repeated commands
Several booleans can describe impossible combinations
A reservation with is_pending, is_confirmed, and is_cancelled flags can accidentally become confirmed and cancelled at the same time. When states are mutually exclusive, one named state often expresses the model more clearly. An enum gives the states names and prevents arbitrary spellings from silently becoming new states.
A state machine describes which transitions are allowed and what each transition does. A pending reservation may be confirmed or cancelled. A cancelled reservation may be terminal in today's model. A confirmed reservation may have a separate cancellation policy. These are domain decisions, not conclusions supplied by enum syntax.
Commands should enforce the transition table. Setting a status field directly bypasses the rule. A confirm method can reject a cancelled reservation and make a repeated confirmation either a no-op or a documented rejection. Choose one policy and test it. Repeated requests are common in real interfaces, so their meaning should not be accidental.
A small explicit lifecycle Python 3.11+
from enum import Enum
class State(Enum):
PENDING = "pending"
CONFIRMED = "confirmed"
CANCELLED = "cancelled"
class Reservation:
def __init__(self):
self._state = State.PENDING
@property
def state(self):
return self._state
def confirm(self):
if self._state is not State.PENDING:
raise ValueError("cannot confirm this reservation")
self._state = State.CONFIRMED
reservation = Reservation()
reservation.confirm()
print(reservation.state.value)
Expected result
confirmed
One allowed transition. A pending reservation can follow a defined transition into confirmed state; future commands must check the new state rather than relying on old flags.Scroll horizontally to read the full diagram on a small screen.
A confirmed reservation may also require a nonempty member identifier, a valid copy identifier, and a confirmation timestamp. Those relationships must be maintained with the state. Changing only the enum can still leave an impossible record. Treat the transition as a coordinated operation that establishes all required facts or rejects without partial mutation.
Do not create a separate class for every state unless the behavior is complex enough to justify it. A small transition table and one enum may be clearer. The state pattern becomes useful when many operations vary by state and conditional branches have become difficult to maintain. Patterns should reduce complexity in a real problem, not demonstrate that the author knows pattern names.
When state is persisted, concurrent commands need a storage-level consistency policy. Two processes can both read pending and attempt incompatible transitions. An in-memory if statement does not coordinate them. Version checks, transactions, or another appropriate mechanism must protect the durable transition. The domain model states the rule; the persistence boundary must enforce it across competing callers.
Translate data deliberately at the application edge.
By the end of this chapter
Separate domain objects from transport records
Validate reconstructed data and avoid unsafe object loading
A database row is a representation, not the domain itself
A domain object expresses behavior and rules. A JSON object, database row, or HTTP body is a representation used for storage or communication. Those representations may use different field names, optional fields, and versioning rules. Treating them as the same thing can force transport details into every domain method.
A data transfer object is a simple representation used to cross a boundary. It should contain the information the receiver needs, not every internal field reachable from the original object. Sending an entire member object can expose email addresses, internal flags, or nested relationships that the interface never intended to publish.
Reconstruction is another input boundary. A record loaded from storage can be old, malformed, or inconsistent with current rules. Validate the relevant facts before using it as a trusted domain value. If historical records require migration, define that process rather than silently changing their meaning in an ordinary getter.
Use an explicit public representation Python 3.11+
Identity and consistency survive beyond one process
An entity's identity should not be its current memory address. A stable identifier lets a program recognize the same copy after a restart, across a network response, or inside a saved loan record. The identifier's uniqueness rules need a clear authority. Two independent processes choosing the next integer from an old snapshot can create collisions without coordination.
Do not serialize arbitrary executable objects from untrusted sources. Formats that reconstruct object behavior can introduce security risks. A plain data format with explicit validation is easier to inspect, version, and constrain. Even JSON requires limits on size, accepted fields, and value ranges; a harmless-looking format does not eliminate input validation.
A repository abstraction can express operations the use case needs, such as get_copy and save_loan. Avoid an abstraction that merely reproduces every database-driver method under a new name. Define ordering, transaction boundaries, missing-record behavior, and concurrent-update handling where callers rely on them. A narrow repository is useful because of its contract, not because every application must have a class named Repository.
Use principles to diagnose change pressure without adding unnecessary layers.
By the end of this chapter
Apply cohesion and dependency principles pragmatically
Refactor under behavioral tests
Ask what changes together
Cohesion describes how closely a component's responsibilities belong together. Coupling describes how strongly components depend on each other's details. A class that calculates loan policy and formats HTML changes for two unrelated reasons. Separating those responsibilities can reduce the chance that a visual change damages a domain rule.
The single-responsibility principle is often reduced to one method per class, which misses its purpose. A class can have several operations that maintain one coherent rule. Conversely, one enormous method can combine unrelated responsibilities. Ask which stakeholder or rule causes a change, and whether that change should require editing this component.
The open-closed principle encourages stable extension points when new implementations are a real source of variation. It does not mean never edit existing code. A policy interface can make adding another discount straightforward, but a speculative interface for a feature nobody needs can make today's code harder to understand. Prefer evidence from actual changes over imagined future flexibility.
Inject one real variation without a hierarchy Python 3.11+
Refactoring changes internal structure while preserving the relevant observable behavior. Begin by writing tests for the existing contract, including awkward boundaries. Then make one small structural change and run those checks. If a behavior is intentionally changing, describe that separately so a reviewer can distinguish a refactor from a new policy.
A useful dependency direction keeps high-level policy from depending on low-level setup details. A calculation should not need a specific database connection merely to add two values. That does not require an abstraction around every library call. A direct standard-library call inside a well-bounded adapter can be simpler and clearer than a generic wrapper with no independent contract.
Smells are investigation prompts, not automatic verdicts. A long parameter list may indicate missing grouping, or it may be an honest representation of an operation with many inputs. A duplicated line may be harmless, while duplicated business rules can drift dangerously. Read the behavior, understand the change pressure, and choose the smallest improvement that reduces a demonstrated risk.
A safe refactoring loop. Capture the observable behavior, change one structural concern, and check that the agreed contract still holds before continuing.Scroll horizontally to read the full diagram on a small screen.
Build a complete original model, then test the claims it makes.
By the end of this chapter
Combine value objects, state rules, composition, and tests
Explain exactly where concurrency and persistence remain outside scope
State the rules before reading the implementation
The capstone tracks a fixed set of copy identifiers and active loans. Each copy can have at most one active loan. A member can have at most two active loans by default. A successful checkout creates an immutable Loan value with a due date fourteen days after the injected clock's date. A return requires the matching member and copy. Rejected operations leave active loans unchanged.
The model is intentionally single-process and in-memory. It does not establish that a member is registered, send notifications, calculate fines, handle reservations, or coordinate concurrent database writes. Those are useful extensions, but calling them complete without implementation would hide the actual boundary of the program. A small model is trustworthy when its scope is explicit and its rules are observable.
Circulation owns the mutable collection of active loans. Callers receive Loan values and tuple snapshots rather than the internal dictionary. The clock is a supplied callable, so tests do not depend on the real date. The service validates before storing the new loan, then performs one dictionary update. This organization provides a clear local failure boundary while remaining honest about the absence of a durable transaction.
A focused circulation model. The caller requests checkout from Circulation. Circulation checks the fixed copy catalog and current active loans, then returns an immutable Loan value.Scroll horizontally to read the full diagram on a small screen.Save as circulation.py and run with Python 3.11+ Python 3.11+ · circulation.py
from dataclasses import dataclass
from datetime import date, timedelta
class LoanRejected(ValueError):
pass
@dataclass(frozen=True)
class Loan:
copy_id: str
member_id: str
due: date
class Circulation:
"""Single-process teaching model; not a concurrent database service."""
def __init__(self, copy_ids, today, limit=2):
if limit < 1:
raise ValueError("positive limit required")
self._copies = frozenset(copy_ids)
if any(not isinstance(value, str) or not value for value in self._copies):
raise ValueError("nonempty copy identifiers required")
self._today = today
self._limit = limit
self._loans = {}
def loans_for(self, member_id):
return tuple(loan for loan in self._loans.values()
if loan.member_id == member_id)
def checkout(self, member_id, copy_id):
if not isinstance(member_id, str) or not member_id:
raise LoanRejected("member identifier required")
if copy_id not in self._copies:
raise LoanRejected("unknown copy")
if copy_id in self._loans:
raise LoanRejected("copy already on loan")
if len(self.loans_for(member_id)) >= self._limit:
raise LoanRejected("member limit reached")
loan = Loan(copy_id, member_id, self._today() + timedelta(days=14))
self._loans[copy_id] = loan
return loan
def return_copy(self, member_id, copy_id):
loan = self._loans.get(copy_id)
if loan is None or loan.member_id != member_id:
raise LoanRejected("matching loan not found")
del self._loans[copy_id]
return loan
def expect_rejected(action):
try:
action()
except LoanRejected:
return
raise AssertionError("expected a rejected operation")
def main():
service = Circulation(["C-1", "C-2", "C-3"],
lambda: date(2026, 12, 1), limit=2)
first = service.checkout("M-1", "C-1")
assert first.due == date(2026, 12, 15)
expect_rejected(lambda: service.checkout("M-2", "C-1"))
service.checkout("M-1", "C-2")
expect_rejected(lambda: service.checkout("M-1", "C-3"))
assert len(service.loans_for("M-1")) == 2
expect_rejected(lambda: service.return_copy("M-2", "C-1"))
assert len(service.loans_for("M-1")) == 2
service.return_copy("M-1", "C-1")
service.checkout("M-1", "C-3")
expect_rejected(lambda: service.checkout("M-1", "missing"))
print("2 active loans; all boundary checks passed")
if __name__ == "__main__":
main()
The first checkout establishes a due date of 15 December 2026 from a fixed date of 1 December. A second member cannot borrow the same copy. After the first member takes a second copy, a third checkout is rejected because the member has reached the limit. A wrong-member return is rejected without changing the two active loans. Returning the correct copy frees one slot, allowing a later checkout.
Extend the test set before extending the implementation. Cover an empty catalog, an empty member identifier, an unknown copy, exactly the limit, one beyond the limit, a successful return, a repeated return, and returning a copy borrowed by another member. Check the state after each rejected operation. The included assertions are learning checks, not a replacement for runtime input validation; Python can disable assert statements in optimized mode.
The model uses the copy identifier as a dictionary key, making the one-active-loan-per-copy rule visible in the representation. That representation helps, but the check followed by update is not safe across independent processes. A persistent implementation needs a unique active-copy constraint and a transaction or another appropriate concurrency mechanism to protect the member limit. Test those adapter guarantees against the actual storage system.
For a next project, add a repository boundary, a registered-member lookup, and a notification event after successful checkout. Keep notification delivery failure separate from whether the loan exists. Add a due-date policy collaborator only when real variation such as member categories or closure dates appears. Every extension should name its contract, its failure behavior, and the new test that demonstrates it.
These solutions show a valid line of reasoning. Compare assumptions and intermediate steps, rather than only the final number or output. Other implementations can be equally good when they preserve the stated contract.
Chapter 1 · Start with a model, not a class diagram
Solution 1.1
One use case is: add a title to a member’s list and return its position. Failures might include an empty title and a duplicate entry when duplicates are forbidden. The contract should state whether an existing entry is returned or an error is raised. Only then decide whether a ReadingList object is needed to preserve ordering and uniqueness.
A title describes shared bibliographic information. A copy has its own identity and borrowing state. If one copy is checked out, another can remain available. Combining the concepts would make availability ambiguous or force duplicated title information into every operation.
Chapter 2 · Objects, identity, and shared references
Solution 2.1
The dictionary copy is shallow. The outer dictionaries are different objects, but their tags entries initially refer to the same list. Appending through either path changes that list. Copy the nested value deliberately or use immutable nested values if independence is required.
Usually no. A snapshot can describe the same member at a moment in time, while registration is a distinct operation that assigns a new identity and enforces uniqueness. A generic deep copy cannot decide those business rules safely.
No. The caller receives the same mutable list and can modify it without rebinding the property. Return a suitable snapshot or an interface that exposes only the required operations. Consider nested mutable objects separately.
Confirm that remaining still equals its previous valid value. A failed operation should not partially apply the prohibited transition. Also test spending exactly the remaining amount and spending zero if zero is allowed by the contract.
Chapter 4 · Construction, lifetime, and usable objects
Solution 4.1
An object can be discarded because a request ended, a cache was cleared, or a process stopped. None of those events proves a physical return. The return must be an explicit validated operation persisted according to the application’s reliability needs.
The first email may already have been sent even if the caller did not see success. Reconstructing the object can send another email. Keep domain creation separate from external notification, and use an explicit idempotency or delivery policy where duplicate side effects matter.
No. Frozen initialization blocks ordinary attribute rebinding, not mutation inside a contained list. Use a tuple of immutable values or define a stronger representation policy when deep immutability matters.
Equal objects must have equal hashes. The reverse is not required: collisions are allowed and resolved by equality checks. Fields used in equality and hashing should remain stable while the object is used as a key.
Sending is a dependency of one reporting workflow, not the identity of a report. Compose a sender or pass a sending function into the coordinator. This makes a file-based or in-memory delivery option possible without inventing misleading subtypes.
When variation is a single operation with no related lifecycle or state, a callable can be enough. A class becomes useful when several operations share a contract, when state must be protected, or when a resource lifecycle needs a clear owner.
Only if the contract permits both meanings or the caller does not depend on durability. If successful return promises durable storage, a merely buffered implementation does not fulfill it. Add an explicit flush or commit contract when that distinction matters.
No. It can require method definitions and communicate a family, but an implementation may still return incorrect results or violate state rules. Contract tests and concrete behavioral review remain necessary.
A caller that receives the parent type expects save to perform a permitted write or fail only for documented conditions. A subtype that rejects every write cannot fulfill that capability. Depend on a read-only interface for readers and a write-capable interface for writers instead.
Accepting additional inputs is usually compatible with callers that already stay within the parent’s accepted set, provided the original promises remain true. Rejecting previously valid inputs is the dangerous strengthening of preconditions. Additional behavior still needs clear documentation for callers using the concrete type.
It should also verify that the copy remains available, the member’s existing loans are unchanged, and no successful-checkout event was recorded. The rejected command must preserve the stated invariant, not merely produce the expected exception type.
No. Once an external side effect has occurred, changing local fields cannot retract it. Move side-effect coordination into an explicit application workflow with a suitable delivery, idempotency, or reconciliation policy. Keep the pure domain decision testable separately.
Pass a fixed date into the calculation, or supply a clock callable returning that date. Test before, on, and after the due date. The production wiring supplies the real clock, while the domain calculation stays deterministic.
A fake isolates the use-case logic and makes failures easy to reproduce. An adapter integration test verifies real query behavior, serialization, ordering, transactions, and error translation. A passing fake-based test cannot establish that the production adapter fulfills those contracts.
Chapter 11 · Test behavior, not private arrangement
Solution 11.1
Review whether the test was coupled to representation. If order or duplicate behavior is a public requirement, assert it through the public interface. If the private list was incidental, update the test to observe the contract so future safe refactoring remains possible.
It is meaningful when sending or scheduling the notification is part of the use-case contract, especially when actual delivery is outside the unit test. Verify the required event and relevant fields. Avoid asserting unrelated internal helper calls that merely reflect the current implementation.
Chapter 12 · State machines make lifecycle rules visible
Solution 12.1
With independent booleans, both flags can be true even if the domain forbids that combination. One enum value expresses exactly one named state at a time. Related facts such as identifiers and timestamps still require their own invariant checks.
Both can read pending before either writes, then apply conflicting transitions. The durable update needs a consistency mechanism such as a transaction or version-based conditional update. A class’s local method checks only the state it currently sees.
Chapter 13 · Persistence without exposing the whole object
Solution 13.1
Internal fields may include private data, security flags, or implementation relationships. Automatic whole-object output can expose them when the class changes. Define an explicit public data representation and test its allowed fields.
Memory identity is local to a runtime object and does not provide durable domain uniqueness across restarts or processes. Assign and store a stable domain identifier with a defined uniqueness policy, then reconstruct objects using that identifier.
Chapter 14 · Design principles as questions, not commandments
Solution 14.1
No. Several related operations can form one cohesive lifecycle. Review whether they share one meaningful responsibility and whether unrelated policies are mixed in. Counting methods is not a substitute for understanding behavior and change pressure.
Introduce it when callers need to work with meaningful alternatives, when a boundary needs testing, or when repeated changes reveal a stable seam. Avoid creating speculative layers solely because a future requirement might someday appear.
Chapter 15 · Capstone: model a small circulation desk
Solution 15.1
Return a known loan successfully, record the remaining loans, then attempt the same return again and expect LoanRejected. Confirm that the remaining loans are identical to the recorded snapshot. This tests both the rejection and the failure guarantee rather than only the exception type.
The adapter needs durable enforcement of one active loan per copy and coordinated checking of the member limit. A transaction, suitable locking, or a correctly designed conditional update must protect the operation across workers. An in-memory fake can test workflow decisions but cannot prove that the real database enforces those competing updates.
An explicit type family that can require implementations of abstract methods. Chapter
Aliasing
Several names or references reaching the same object. Chapter
Class
A definition that groups behavior and describes how instances are created. Chapter
Cohesion
How closely a component’s responsibilities belong together. Chapter
Composition
Building an object’s behavior from collaborators it contains or uses. Chapter
Constructor
Initialization behavior that establishes an object’s starting state. Chapter
Coupling
The degree to which components rely on each other’s details. Chapter
Data transfer object
An explicit data representation used across a storage or communication boundary. Chapter
Delegation
Passing a focused responsibility to another component. Chapter
Dependency injection
Supplying required collaborators instead of locating them invisibly inside a component. Chapter
Encapsulation
A boundary that hides representation and exposes operations preserving a contract. Chapter
Entity
A domain object recognized by stable identity while its descriptive state may change. Chapter
Equality
Whether a type’s comparison says two values should count as equal. Chapter
Failure guarantee
The promised result and state after an operation fails. Chapter
Fake
A simplified working implementation used in tests. Chapter
Hash contract
Equal hashable objects must have equal hashes, with key-relevant state stable during use. Chapter
Identity
Whether two references reach the very same object. Chapter
Immutability
A policy that prevents relevant state from changing after creation. Chapter
Invariant
A rule preserved at defined public boundaries. Chapter
Lifecycle
The meaningful states and transitions of a resource or domain concept. Chapter
Mock
A test double commonly used to verify meaningful interactions. Chapter
Object
A runtime instance with identity, type, and value or state. Chapter
Polymorphism
Using different implementations through a common behavioral contract. Chapter
Postcondition
A fact an operation promises after successful completion. Chapter
Precondition
A fact a caller must satisfy before an operation. Chapter
Protocol
A structural description of operations a caller expects. Chapter
Refactoring
Changing internal structure while preserving relevant observable behavior. Chapter
Shallow copy
A new outer structure containing references to existing nested values. Chapter
State machine
Named states and defined transitions between them. Chapter
Substitutability
The ability to use a subtype while retaining the parent contract’s expectations. Chapter
Test seam
A boundary where an implementation can be replaced to isolate behavior in a test. Chapter
Value object
A value defined by meaningful components rather than identity. Chapter
Read and watch with a purpose
Reading and video library
Use the chapter source links to choose a relevant next explanation. Each entry below states what it adds. Documentation links may evolve; edition 2026.12 records the assumptions used here.
Watch the official 2016 lecture for another introduction. Historical course examples use an older Python version; this book’s runnable examples target Python 3.11+.
If a paragraph needs a clearer example, a command changes, or a diagram hides an important assumption, propose a correction in the open-source repository. Explain the issue and add a source or a reproducible example.
Original OpenLearning instructional text and diagrams: CC BY-SA 4.0. Original code: MIT. External material retains its own copyright and license. This book links to authorized resources; it does not relicense them.