An invariant is a condition that must remain true for a software object or component. Encapsulation protects that condition by preventing clients from bypassing the code that maintains it. section 5.5
A well-designed API exposes observable behavior while hiding implementation details. Publishing an operation used only to preserve an invariant leaks internal mechanics into client code. section 5.2 section 5.5
Use these rules when designing an invariant-preserving object:
- Expose operations or state that help clients achieve their goals. section 5.5
- Keep invariant-maintaining operations private when clients do not need to call them directly. section 5.2
- Make client code express its goal directly instead of coordinating internal steps. section 5.2
Normalize a user name without leaking the invariant
User requires names to be trimmed and limited to 50 characters. A fragile API exposes NormalizeName, forcing UserController to call it before assigning Name. A simpler API makes NormalizeName private and invokes it inside the Name setter, leaving the client with only user.Name = newName.











