Encapsulation protects invariants by bundling state with operations that preserve valid outcomes and hiding implementation details behind a public API. A client should invoke one operation for one business action, rather than coordinate internal steps itself. section 3.1 section 5.5
A purchase API that preserves consistency
A well-encapsulated purchase exposes one call: customer.Purchase(store, Product.Shampoo, 5). That operation both transfers the product and reduces inventory. Requiring a second call, such as store.RemoveInventory(success, Product.Shampoo, 5), lets clients perform only half the operation and risks an invariant violation. section 3.1
Use these rules to recognize and improve encapsulation:
- Treat multiple client calls for one action as a possible API design problem, not merely a test-structure problem. section 3.1
- Expose operations or state only when they help clients achieve their goals; keep other implementation details behind the private API. section 5.5
- Judge encapsulation by whether clients can bypass invariants through the public API, rather than by access modifiers alone. section 5.5
- In hexagonal architecture, keep domain logic behind application services so external applications have no direct access to the domain layer. section 5.5













