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 🙂

Where to go Next

This tutorial comes straight out of The Complete iOS Developer Course. Over 40 hours long it contains everything you need to create awe inspiring apps fast!

Click here to check it out!

What is Object Oriented Programming? Encapsulation

Leave a Reply

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

Share This

Want this Post in Easy to Understand Video Form?

Then get the Complete iOS Developer Course. Over 50 hours of pure Swift coding goodness designed to turn you into a coding master!

One Time Offer - $9! Click to Get it!



WARNING: Once this box is closed the offer will not be shown again.

Thank you!