HeadlinesBriefing favicon HeadlinesBriefing.com

Encapsulation for Testable Code

DEV Community •
×

A DEV Community article demonstrates how encapsulation transforms a simple `Wallet` class from a fragile data holder into a robust domain object. The author contrasts a non-encapsulated design—where business rules live in a separate `WalletRepository`—with an encapsulated version that keeps state private and exposes a single domain operation.

The key takeaway is that encapsulation moves validation logic directly into the domain object itself. This prevents callers from bypassing business rules, like setting a negative balance directly. Tests then verify the domain's behavior rather than enforcing a fragile convention about correct usage, making the codebase harder to misuse.

Encapsulation provides lasting benefits: tests become more meaningful, refactors break fewer checks, and invariants are enforced consistently. It turns domain objects into the authority over their own correctness, which is critical for maintaining stable applications as they grow in complexity.