Encapsulation

Encapsulation#

Encapsulation is containing all important information inside an object, and only exposing selected information to the outside world. Attributes and behaviors are defined by code inside the class template. Encapsulation hides the internal software code implementation inside a class, and hides internal data of inside objects. Encapsulation requires defining some fields as private and some as public.

  • Private/ Internal interface – methods and properties, accessible from other methods of the same class.

  • Public / External Interface – methods and properties, accessible also from outside the class.

Let’s use a car as a metaphor for encapsulation. The information the car shares with the outside world - through blinkers to indicate turns, are public interfaces. In contrast, the engine is hidden under the hood - it’s a private, internal interface. When you’re driving a car down the road, other drivers require information to make decisions, like whether you’re turning left or right. However, exposing internal, private data like the engine temperature, would just confuse other drivers.

Benefits of encapsulation:#

  • Adds security: Only public methods and attributes are accessible from the outside

  • Protects developers from common mistakes: Only public fields & methods accessible, so developers don’t accidentally change something dangerous

  • Protects IP: Code is hidden in a class, only public methods are accessible by the outside developers

  • Supportable: Most code undergoes updates and improvements

  • Change internal code in class without alerting users: As long as the public attributes & methods stay the same, internal code can be updated without changing existing objects

  • Hides complexity: No one can see what’s behind the object’s curtain!