Object oriented programming has a few core concepts. One of the most fundamental is Encapsulation. Here’s a really simple explanation for it:

  • Encapsulation is hiding away of functionality.

What does that mean? Perhaps a real world example will be good here:

  • If you have a  BMW, you don’t particularly care how the engine does what it does – you only care about getting MAXIMUM POWER when you stamp your foot down. How the engine fires, the ratio of air to gas or lubrication details are irrelevant.

Programming encapsulation is exactly the same. When you write a piece of code try to think about it in the same way. You should only expose the inputs and the end result (in reality it’s a little more messy than that).

That means you always want to hide away AS MUCH CODE AS POSSIBLE.

What does “hide” mean here? Well, let’s use a class as an example:

In the above snippet I have created an access function / method to get the top speed which seems like overkill. Why didn’t I just use the ‘topSpeed’ variable?

Let’ say that in the future all my ‘Cars’ get an upgrade which gives them a 10% bump in speed. I can now do this:

The way that other parts of my program use this class is still the same. They’ll all access the GetTopSpeed function and have no idea what’s going on in side it. We have hidden away the implementation quite nicely, and that, ladies and gentlemen, is encapsulation in a nut shell.

Hide away as much functionality as you can.

Right now, it seems a little like overkill to write all that code just to encapsulate a 10% bump in values. But imagine this:

  • You are accessing a web feed
  • You’re processing that feed data
  • The data structure changes one day (no new data is added, just the structure changes) forcing you to change your code
  • Now you only have to change code in ONE place in order to parse the data
  • The rest of your app is blissfully unaware that this has happened because it doesn’t need to know!

Always encapsulate. I promise that your coding life will be MUCH easier for it 🙂

What is Encapsulation – Object Oriented Programming

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share This

Exhausted by your 9 - 5?

Would you prefer to work for half the time and earn double? The first step to your freedom is understanding how apps make money. Simply enter your email below and I will send you a free PDF describing the process.

If you're serious about improving your life then do not miss this opportunity.

You have subscribed! Please check your email to confirm this subscription and to receive your item!