All lessons in Software Engineering: Programs, Systems, and Maintainable Software
Domain Models and State Invariants
Model copy and loan states and identify invalid transitions before implementation.
35 minutes · Free lesson
What you will learn
- Express a lending rule as an invariant over identifiable entities.
- Trace allowed and rejected state transitions, including failure paths.
- Distinguish a stored fact from a value derived from other facts.
A library can own three physical copies of the same title. A member borrows one copy, returns it, and later borrows another. A design that stores only a book title and an available flag cannot answer which object changed or preserve a borrowing history. Before selecting classes or tables, decide what the system must remember and what must always remain true.
This lesson supplies the domain model used throughout the course. You will model a small lending desk, not every operation of a real library. Renewals, fines, reservations, and digital licensing are outside the first release. Drawing that boundary makes the rules small enough to reason about and test.
Identify things whose histories differ
An entity has an identity that persists while its attributes change. A title describes a work; a copy is an individual lendable object. Two copies can share a title and have different current borrowers. A member has a stable identifier even if their displayed name changes. A loan records a relationship between one member and one copy over time.
A value object is defined by its value rather than by an independent history. A due date can be represented as a date value. Two equal due dates are interchangeable for the rule that compares dates. A physical copy is not interchangeable with another copy merely because both have the same title.
Use identifiers in relationships and display names in presentation. If a member changes their name, historical loans should not need to be reassigned. If a title is corrected, its copies keep their identities. This is the practical reason for separating identity from the text a person sees.
| Concept | Identity | Facts to retain |
|---|---|---|
| Title | title_id | Display title and author description |
| Copy | copy_id | Which title it represents; retirement state |
| Member | member_id | Display name; eligibility state |
| Loan | loan_id | Copy, member, borrowed date, due date, returned date |
Avoid inventing a separate entity for every noun in a requirement. A lending button is an interface element, not necessarily a domain entity. Conversely, a relationship deserves its own record when it has a history or meaningful attributes: a loan has dates and a return event, so a permanent member-to-copy field is insufficient.
Write invariants as predicates
An invariant is a property that must hold at a defined boundary. For this service, committed records must satisfy these rules: each copy references an existing title; each loan references an existing copy and member; a copy has at most one active loan; the due date is not earlier than the borrowed date; a recorded return is not earlier than borrowing.
Define active precisely: a loan is active when its returned date is absent. The invariant is therefore a count over active loans for each copy, not a guess based on the most recent record. Past loans remain valid historical records after return.
A useful invariant names its scope and observation point. “No duplicates” is weak because it does not say which combination is unique. “For every copy, the number of committed loans with no returned date is at most one” is checkable. During a transaction, temporary intermediate values may exist; the public operation must either produce a valid committed state or leave the prior state unchanged.
Specify commands as transitions
A command requests a state change. Borrow takes a member, copy, borrowed date, and due date. Its preconditions include valid references, an eligible member, a lendable copy, valid dates, and no active loan. Its successful postcondition is a new active loan with those facts. Its failure postcondition is that no partial loan remains.
Return takes an existing active loan and a return date. It sets the return date while preserving the original borrowing facts. In this course, returning an already returned loan is rejected with an explicit domain error. Another product could choose a different rule, but the rule must be specified before implementing and testing it.
Some states are combinations rather than a single enum. A copy may be retired and still have an active loan awaiting return. If the product allows that combination, an enum containing only available, borrowed, and retired loses information. Model retirement and the active loan separately, and define which commands are allowed for each combination.
Worked example
Follow one copy through its history
- Copy C17 represents title T4 and is not retired. It has no active loan. The active-loan count is zero.
- Member M8 borrows C17 on 2026-10-01, due 2026-10-15. Loan L21 is created with no returned date. The active-loan count becomes one.
- Member M9 attempts to borrow C17 on 2026-10-02. Reject the command and keep L21 unchanged; creating a second active loan would violate the invariant.
- L21 is returned on 2026-10-10. Keep L21 and record its return date. The active-loan count becomes zero, although the historical-loan count remains one.
- M9 borrows C17 on 2026-10-11. Create L22 rather than overwriting L21. There are two historical loans and exactly one active loan.
Find the boundary that can enforce the rule
A check inside one function protects only callers using that function and only the execution it observes. Two callers can both observe availability before either writes. The domain rule stays the same, but its enforcement must live at a boundary that sees competing writes. Later lessons implement a database constraint and transaction around this rule.
Use multiple layers for different purposes. The interface can explain why borrowing is unavailable. The domain service can report a meaningful rejection. The database can reject an invalid final relationship even if another caller bypasses the interface. These layers cooperate; an interface check alone is not the invariant's final enforcement point.
The same reasoning applies to deletion. Removing a title while copies still reference it would break the model. Decide whether to reject deletion, archive the title, or perform a deliberate cascade. A default cascade is a product behavior with consequences, not simply a convenient database option.
Turn the model into a review artifact
A compact model review contains an entity table, five invariants, command preconditions and postconditions, and several transition traces. It should include one rejected command, one historical query, and one competing-command scenario. A reviewer should be able to explain what remains unchanged after failure.
The model is useful only if implementation and tests can refer to the same rules. Give invariants short names such as one-active-loan and valid-loan-dates. Put those names in test descriptions and design notes. When a requirement changes, trace the affected rules rather than editing fields opportunistically.
Exercise
A design stores member_name and title_text directly on a current_borrowing record and deletes that record on return. Identify three questions it cannot answer reliably and propose the minimum identity and history changes.
Check your answer
It cannot distinguish physical copies with the same title, reliably associate loans after a member name changes, or report past borrowing after records are deleted. Add stable member, title, and copy identifiers; store a loan record with its own identifier and borrowing/return dates; retain returned loans. Display names may be resolved through their identifiers, with explicit snapshots only if historical display text is required.
Exercise
A copy has one returned loan and one active loan. A developer counts all its loans and rejects the state because the count is two. State the actual invariant and give a test that exposes the mistake.
Check your answer
Count only loans whose returned date is absent; that count must be at most one per copy. Create a loan, return it, then borrow the same copy again. The second borrowing must succeed, leave the first history intact, and produce exactly one active loan.
Exercise
A return dated 2026-09-30 is requested for a loan borrowed on 2026-10-01. Specify the failure result, the stored state afterward, and one assertion beyond checking an error message.
Check your answer
Reject the invalid date with a domain error. The loan must remain active with its original borrowed and due dates and an absent return date. Assert that all stored loan fields remain unchanged; also assert that the copy still has exactly one active loan.
Summary
A domain model separates stable identity, historical relationships, and derived state. Invariants name the properties valid committed records must satisfy. Commands need both success and failure postconditions. Trace the rules before choosing their enforcement mechanisms.
Next action
Write the entity table and transition rules for one additional command, such as retiring a copy. Decide explicitly whether an active loan prevents retirement and how the item can still be returned.