This is part 5 of a series. To get the most out of these posts, read them in order:
According to Wikipedia (the Patron Saint of Crowd-Sourced Information):
“Encapsulation, Inheritance , and Polymorphism are the three pillars of object-oriented programming.”
So far, we’ve talked about one of those concepts: Inheritance. Now, we’ll talk about Encapsulation.
Encapsulation is a technique in Object Oriented Programming that allows you to restrict the ways a user can interact with an Object.
Part 5: Encapsulation
Every parent knows how hard it is to feed their kids broccoli, and I frequently wish I could just smash some green vegetables up against my children’s skin and have them magically absorb the nutrients.
Unfortunately, while that might work great for broccoli, it would leave my kids’ internal organs quite vulnerable. Kids have a tendency to touch a lot of disgusting stuff, and we wouldn’t want them to absorb worm guts and puppy drool.
To protect the important organs inside the Child Object, we’re going to create an Interface, or “method for interacting with an object”. Our Interface is a method called “Eat with Mouth”. Now food can only go into a Child Object via the Eat with Mouth Interface. This Interface also has a Taste feature, which Validates that anything going in is not “icky”.
Unfortunately for us, Broccoli does not pass the Ickiness Validation.
As you can see, there are upsides and downsides to Encapsulation.
The upside is that it protects the internals of your Object from being affected by Objects and Methods that you don’t want it exposed to. (This is a pretty enormous upside).
The downside is that it makes it harder for us to access those internals when we want to do something unconventional. It’s the technological equivalent of having to coo “Here comes the choo-choo” just to get one bite of broccoli past the Taste Validation. (Not too big a sacrifice to prevent liver failure).
In a computer program, the “Internal Organs” that you are trying to protect are bits of information. If important pieces of information get altered, your program might do something unexpected like Crash Whenever a User’s Name is Bob or Build a Militia and Invade France.
Encapsulation is the process of bundling our data and methods together, in order to protect that data from being accessed or changed in ways that it shouldn’t. Hiding information is called….wait for it…..
You might hear the term Information Hiding used as a synonym for Encapsulation, but I like to think that “Information Hiding” is the purpose behind Encapsulation, and Encapsulation is the process by which information is bundled with methods and hidden from meddling users.
There is, however, apparently some debate around the exact definitions, and if you care about that, Google knows better than I.
Next up: Part 6: Data Types