Encapsulation and Everything in Between

Encapsulation according to Wikipedia has two definitions

A language mechanism for restricting access to some of the object’s components.

A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

If that doesn’t make any sense to you, don’t worry it doesn’t really make that much sense to me either. As usual in the world of computers things have been over complicated and those definitions are not meant for beginners. I present a different explanation of encapsulation.

Believe it or not you have been using encapsulation your entire life. As an example from my childhood and parenting experiences, when my children were a little younger I would go to their rooms and very patiently tell them each and every item that needed to be put away and how to do it. Now that I feel they are old enough I have stopped telling them all the details and have now simply said for them to clean their rooms.

That is the essence of encapsulation. When I tell them to clean their room I am actually telling them to pick-up all their toys, throw away all the trash, and make their bed. As a programmatic example here is what programmers call psuedocode for both the unencapsulated version and the encapsulated version of what I explained above.

Without encapsulation

- Take all toys off your bed
- Straighten your bed sheets
- Put all your toys in your toy box
- Pick up all the trash
- Put the trash in your trashcan

With encapsulation

- Clean your room

The important thing to note here is that in the first version, the one without encapsulation, we have to dictate all the details of what to do and what order to do it in to accomplish the task of a clean room. In the second version, the one with encapsulation, we don’t care how the room gets clean as long as it gets clean. This is the benefit you get from encapsulation. You are able to take groups of related tasks and move them to another location and even reuse them as often as you would like or need.

Comments are closed.