How I finally understood what Encapsulation is

Christian Vasquez - Mar 15 '22 - - Dev Community
_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 🤝

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .