When I was first presented with encapsulation and shown an example of its implementation I wondered, “Why? You haven’t really stopped someone from getting to that private data you just added a public method to act as a willing accomplice in the crime.” Then I realized, it’s not about security, it’s about integrity and logical delegation of responsibility.
I shall illustrate…
Imagine we have three fictional people, we’ll call them …oh I don’t know …. Lets call them Raj, Clint, and Andy.
Now let’s say these three are sitting at a bar and Andy wants to punch Raj in the head, and Clint is sitting in between them.
Andy could take hold of Clint’s arm and use it to punch Raj in the head.
I shall illustrate…
Imagine we have three fictional people, we’ll call them …oh I don’t know …. Lets call them Raj, Clint, and Andy.
Now let’s say these three are sitting at a bar and Andy wants to punch Raj in the head, and Clint is sitting in between them.
Andy could take hold of Clint’s arm and use it to punch Raj in the head.
This is just silly.
As we can see Andy is not very effective at using Clint’s arm to punch Raj in the head. He could only generate the force of a small girl recovering from the flu.
Andy shouldn’t touch Clint’s arm, he doesn’t know where that arms been.
Its Clint’s arm, wouldn’t it make sense for Clint to throw the punch?
Lets do this a smarter way, lets use….ENCAPSULATION!
Now that’s better! Encapsulation works out better for everyone.
It works out better for Andy, because he doesn’t have to get involved in the process. He wanted Raj punched in the head; uppercut, rabbit punch, short jab it doesn’t matter as long as it happens.
It works out better for Clint, because he doesn’t have to have Andy touching him in inappropriate ways. It’s his arm he knows how to make it punch something.
And it works out better for Raj, because… Ok it doesn’t work out better for Raj but that’s not the point.
The point is encapsulation is good.
Disclaimer: The characters depicted in the above illustration are fictional, any resemblance to actual persons, living or dead, is purely coincidental. The artists involved in this example do not endorse the punching of Raj in the head, or condone violence against Raj in any of its various forms.