intermediate · 26 minute study
A class can protect a rule, not just hold fields
A property that anyone can overwrite cannot protect an inventory rule. Put state changes behind behavior that checks the rule once.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- Copying a value and copying a reference are different — Understand why one assignment leaves the original untouched while another changes an object visible through several variables.
First, build a mental model
An invariant is a statement that remains true before and after every valid operation. Encapsulation narrows the ways callers can change the state so the class can defend it.
- A constructor establishes a valid starting state or rejects construction.
- A public getter with a private setter lets callers observe state without assigning it directly.
- Methods validate a requested transition before changing any fields.
- A class invariant protects one object in this process. Database constraints and transactions are still needed for concurrent persistent updates.
var stock = new StockItem(5);
Console.WriteLine(stock.TryReserve(2));
Console.WriteLine(stock.TryReserve(4));
Console.WriteLine(stock.Available);
sealed class StockItem
{
public int Available { get; private set; }
public StockItem(int initial)
{
if (initial < 0) throw new ArgumentOutOfRangeException(nameof(initial));
Available = initial;
}
public bool TryReserve(int quantity)
{
if (quantity <= 0 || quantity > Available) return false;
Available -= quantity;
return true;
}
}- Construct
The initial valid stock is 5.
- Reserve 2
The request passes; Available becomes 3.
- Reserve 4
The request fails before mutation; Available stays 3.
Production thinking
Take this beyond the example.
Protect the rule at the canonical write boundary as well as in the domain model. Synthetic inventory examples here deliberately omit proprietary financial and statutory rules.
Sources and further reading
Your evidence
unseen is a local learning signal, not a credential or proof of production competence.
Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.
Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.
Next lesson · Records describe values, but with is a shallow copy →