Skip to content

Instantly share code, notes, and snippets.

@xpepper
Last active September 5, 2020 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xpepper/5601953 to your computer and use it in GitHub Desktop.
Save xpepper/5601953 to your computer and use it in GitHub Desktop.

http://gmoeck.github.io/2011/09/20/why-you-should-care-about-encapsulation.html

...when I say encapsulation, I mean "the behavior of an object can only be affected through its API". Or to put it negatively, an object is not well encapsulated when its behavior can be affected without calling its API. Or another way to think about it is that a well encapsulated object draws a solid boundry or wall around itself, and ensures that all the code that changes its behavior is contained within the object itself.

From Growing Object-Oriented Software, Guided by Tests

Encapsulation and Information Hiding

We want to be careful with the distinction between “encapsulation” and “information hiding.” The terms are often used interchangeably but actually refer to two separate, and largely orthogonal, qualities:

Encapsulation

Ensures that the behavior of an object can only be affected through its API. It lets us control how much a change to one object will impact other parts of the system by ensuring that there are no unexpected dependencies between unrelated components.

Information hiding

Conceals how an object implements its functionality behind the abstraction of its API. It lets us work with higher abstractions by ignoring lower-level details that are unrelated to the task at hand.

We’re most aware of encapsulation when we haven’t got it. When working with badly encapsulated code, we spend too much time tracing what the potential effects of a change might be, looking at where objects are created, what common data they hold, and where their contents are referenced. The topic has inspired two books that we know of, [Feathers04] and [Demeyer03].

Many object-oriented languages support encapsulation by providing control over the visibility of an object’s features to other objects, but that’s not enough. Objects can break encapsulation by sharing references to mutable objects, an effect known as aliasing. Aliasing is essential for conventional object-oriented systems (otherwise no two objects would be able to communicate), but accidental aliasing can couple unrelated parts of a system so it behaves mysteriously and is inflexible to change.

We follow standard practices to maintain encapsulation when coding: define immutable value types, avoid global variables and singletons, copy collections and mutable values when passing them between objects, and so on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment