How I finally understood what Encapsulation is
Tags: howifinallyunderstood, kotlin, oop, beginners
Published: 2022-03-15 07:27:03

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

---

## 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](https://c.tadst.com/gfx/1200x630/fb-stopwatch2.png?1)

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:

```kotlin
class Stopwatch {
    
    fun click() {
        // Nothing going on here. Keep reading!
    }
    
}

```

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:

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

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

```kotlin
fun main(args: Array<String>) {
    val stopwatch = StopWatch()
    stopwatch.click()
}
```

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.

```kotlin
class StopWatch {

    private var isRunning: Boolean = false

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

}
```

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:

```kotlin
fun click() {
   if (isRunning) {
      isRunning = false
      println("Stopped")
   } else {
      isRunning = true
      println("Started")
   }
}
```

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

```
Started
Stopped
```

Hooray!

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

```
Started
Stopped
Started
``` 

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z5qvftpv31qst5o6zpdi.png)
 

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](https://dev.to/chrisvasqm/how-i-finally-understood-what-a-class-is--24pl), 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 🤝