Encapsulation
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
π StructureDashed line animations indicate the flow direction of data or requests
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.
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.
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.
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.
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.