Encapsulation

Encapsulation is the process of combining attributes and methods into a single named entity.

 

 

Different levels of visibility can be applied to a class’s members to allow other objects to interact with it at an appropriate level.

 

Only the absolute bare minimum should be visible to external objects. This visibility is controlled by applying specific access levels to the class’s individual members.

 

Only public declared methods should be able to be seen and utilised by external objects.

 

It is these public declared methods that are considered as the class’s interface.

 

 

In this example the other Object can only invoke the public behaviours (in green) and is denied access to the attributes and private behaviours (in red). All of its attributes are enclosed within its methods and may only be accessed and changed by it methods. For instance in the real world, you don’t have to know about the inner workings of the engine, you just have to twist the throttle to accelerate.

 

Any invoking object should not care how the requested object’s methods are implemented, all they should care about is presenting the required information via a message (twist throttle) to the object’s public interface (accelerate) in the correct format, so that it can receive an expected return or action (increased speed).

 

Access to an object’s attributes should only be controlled by the object itself, and no other object should directly change an attribute of another object.

 

This concept is known as data hiding.

 

This is akin to the black box model. We don’t care what goes on inside as long as we get what we want from it, providing we supply the correct information to it.

 

So as long as the interface stays the same, the internal methods of the object can be changed or improved as/if required.

 

Reduces complexity and dependencies, so that a change in one place won’t require multiple changes elsewhere.

Leave a Reply