Conceptly
← All Concepts
πŸ”’

Encapsulation

FoundationsProtecting state behind controlled methods

Encapsulation is the principle of not exposing an object's internal state directly and instead forcing access through approved methods. The goal is not hiding for its own sake, but keeping the rules for state changes inside the object that owns them.

β–ΆArchitecture Diagram

πŸ” Structure

Dashed line animations indicate the flow direction of data or requests

Why do you need it?

If fields can be changed from anywhere, it becomes very hard to guarantee that the object is still in a valid state at any given moment. Validation rules scatter across callers, repeat inconsistently, or disappear altogether.

Why did this approach emerge?

In early procedural styles, data structures and the functions that manipulated them were often separate. As systems grew, the rules around that data spread across many modules, and encapsulation became the way to pull those rules back into a clear boundary around each object.

How does it work inside?

An object usually combines private state with public methods. Outside code sends requests through the public API, and those methods inspect and update internal state only after applying the necessary checks and transformations.

Boundaries & Distinctions

Encapsulation and abstraction overlap, but they answer different questions. Encapsulation is about who may touch state directly and where consistency rules live; abstraction is about which conceptual surface to expose at all.

When should you use it?

Encapsulation is especially important for data whose invalid transitions would immediately create business errors, such as account balances, order states, or inventory counts. For thin DTO-style structures used only to shuttle values across a boundary, heavy encapsulation can add indirection without much payoff.

Guard domain rules -- enforce balance, quantity, and status-transition constraints inside methodsReduce change impact -- change internal representation without rewriting callersBlock invalid edits -- prefer validated methods over arbitrary field mutationStabilize collaboration -- keep rules in one place even when many developers touch the same object