Encapsulation

Encapsulation has two distinct notions, and sometimes the combination thereof.

  • Encapsulation means restricting access to some or all sub-components of a software component.
  • Encapsulation means the bundling of data with the operations that operate on that data.

The second definition originates from object-oriented programming, though equivalent patterns can be applied through other programming styles, too. In object-oriented programming languages, classes are the language-level construct that enable encapsulation of data and methods in a single unit of code.

Encapsulation is a design pattern that realizes the design principles of abstraction and information hiding by protecting data from outside interference and misuse, and freeing implementations to change without forcing every caller to change too.

Best practice is to encapsulate the most volatile sub-components, the elements that are most likely to change in their implementation in the future. This principle is known as encapsulating what changes. This is one of the main mechanisms by which systems are protected from extensive refactorings when any one part of them changes.

Encapsulation is the foundation that makes loose coupling and composition practical.

See also