DEV Community

Cover image for How I finally understood what Encapsulation is
Christian Vasquez
Christian Vasquez

Posted on

How I finally understood what Encapsulation is

_Banner image from [Mackenzie Child](https://dribbble.com/mackenziechild) on Dribbble_

The Intro

As I'm struggling to sleep today, here goes my attempt to try help out anyone out there who's having a hard time trying to understand the concept of Encapsulation.

The What

But before we dive in, let's see what our good-old friend, Wikipedia, defines it as:

In object-oriented programming, encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components

Perfect. Now that's it for today everyone, thanks for reading this post...

Just kidding!

Let's start with an idea:

Imagine we are going to design a code that would represent a Stopwatch (now you're probably guessing why I chose Mackenzie's illustration, aren't you?).

I want you to picture it in your head. If you can't do it, don't worry. Here you go:

Stopwatch image

Notice how we interact with the Stopwatch. It has 1 button that we can click in order to get it started/running. That right there tells us what is the behavior of the Stopwatch or the possible actions we can do with it.

The How

So, in code that would look like this:

class Stopwatch {

    fun click() {
        // Nothing going on here. Keep reading!
    }

}

Enter fullscreen mode Exit fullscreen mode

Now we start adding implementation details to this Stopwatch.

For the sake of simplicity, let's just display a message in the console. (In case you didn't notice already, I'm using Kotlin for this example, but you can get this to work on any other language you prefer, some way or another. But I will leave that up to you).

So, the first thing we are going to add to our click() method is:

fun click() {
    println("Started Stopwatch")
}
Enter fullscreen mode Exit fullscreen mode

If we run this code in our main function, we would get the message on the console.

fun main(args: Array<String>) {
    val stopwatch = StopWatch()
    stopwatch.click()
}
Enter fullscreen mode Exit fullscreen mode

Awesome!

But, what would happen if we call the click() method multiple times? We would get the same message, but that's not the right way to do it. We would like the Stopwatch to be stopped/paused if we click it a second time and then resumed/restarted if we click it a third time.

How can we do that?

Well, we would need a second piece of the puzzle. We already have behavior so... we would need state. A way to "save" some data related to the Stopwatch.

Let's do that.

class StopWatch {

    private var isRunning: Boolean = false

    fun click() {
        println("Started Stopwatch")
    }

}
Enter fullscreen mode Exit fullscreen mode

By adding a Boolean variable we can store and change that value inside of our click() method and change the behavior depending on whether the isRunning boolean value is set to true or false.

Now, notice how we prefixed the definition of this field/property with the keyword private. That's interesting... if something is private then, that means that it can also be public, right?

That's correct!

Now, why did I do that? That is how we can apply Encapsulation (finally, took us long enough to get there).

But let's keep that little word in our background, and let's continue with the Stopwatch implementation.

Here's how I would change the click() method:

fun click() {
   if (isRunning) {
      isRunning = false
      println("Stopped")
   } else {
      isRunning = true
      println("Started")
   }
}
Enter fullscreen mode Exit fullscreen mode

Now, if we call the click() method twice, we will see the messages

Started
Stopped
Enter fullscreen mode Exit fullscreen mode

Hooray!

But... what if we do it three times?

Started
Stopped
Started
Enter fullscreen mode Exit fullscreen mode

We are still good, don't worry 😄

The Why

Now, how about you try something else with the stopwatch object?

Check out what the IDE shows if you type exactly: stopwatch.

Stopwatch methods list

What are all the options you have? The first one would be the click() method we implemented, and then there's a lot of others weird stuff. But focus on how there's nothing that mentions the isRunning property.

No one else knows about it, except you and everyone else reading this post. But that's the beauty of Encapsulation. You can design your objects to be boring and predictable.

It doesn't sound interesting or exciting right now, but trust me... it will once you get your hands into some nightmare code.

The Goodbye

That's it for now, I will try to come up with other ideas and make it into a Series of posts. This one came to me after remembering a good-old post I wrote just a few years ago: How I finally understood what a class is, which you might wanna checkout as well or recommend it to a friend if they are also struggling as we all do in this difficult times.

Without more to say, have a good one and stay safe 🤝

Top comments (6)

Collapse
 
furiabhavesh profile image
Bhavesh Furia

I read a statement somewhere long time back

When a shopkeeper asks you for money, will you give them your wallet to take the money out ? If you do, then you are breaking encapsulation. The same logic applies to classes and access to methods. In general, public getters and setters result in breaking encapsulation

Collapse
 
pedrovarela86 profile image
Pedro Varela • Edited

..and then there's a lot of others weird stuff...

Christian you are writing a technical article, a lot of "weird" stuffs? You should expect the people reading this post are swe or related to programming, otherwise there's no reason why they would be here in the first place.
Reading that phrase simply bothers me a bit and makes me stop reading right away. Next time, make a better explanation of what not "weird" at all stuffs are.

Thank you.

Collapse
 
chrisvasqm profile image
Christian Vasquez

Hi Pedro,

Thanks for your feedback.

I get your point, but I decided to not go into further details as to what those "weird stuff" are in order to not lose the focus of this example since I wanted this to be as beginner friendly and programming language agnostic as possible.

Collapse
 
pedrovarela86 profile image
Pedro Varela

Absolutely, my intention is to be critize you constructively.
Thanks for your post tho.

Collapse
 
jdvasquez profile image
Daniel Vásquez

Great post, Chris. Thank you!

Collapse
 
tariqywsf profile image
Tarek Bohdima

great post i learned the importance of encapsulation lately and it helped me land a job just by showing it off in an assignment project :)