liveBook · Manning

Encapsulation

As explained in Unit Testing Principles, Practices, and Patterns

Encapsulation is the restriction of direct access to an object's internal state and the bundling of that state with controlled operations.

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

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines invariant protection, contrasts single- and multi-call APIs, and connects public behavior with hidden implementation details.
Examples
Uses customer purchases, inventory updates, single-line test actions, and domain boundaries in hexagonal architecture.
What it assumes
Assumes familiarity with objects, clients, methods, public APIs, and private implementation details.
What you can do after
Evaluate APIs by checking whether one operation preserves complete outcomes and prevents clients from bypassing invariants.
How it connects
Connects encapsulation with invariant violations, public APIs, observable behavior, implementation details, and hexagonal architecture.

Also explained in

Compare how 14 books explain encapsulation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.