How I finally understood what Encapsulation is

Banner image from Mackenzie Child on Dribbble

The Intro

As I’m struggling to sleep today, here goes my attempt to try help out anyone out there who’s struggling to understand the concept of Encapsulation.

The What

But before w…


This content originally appeared on DEV Community and was authored by DEV Community

Banner image from Mackenzie Child on Dribbble

The Intro

As I'm struggling to sleep today, here goes my attempt to try help out anyone out there who's struggling 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!
    }

}

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")
}

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()
}

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")
    }

}

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")
   }
}

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

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 🤝


This content originally appeared on DEV Community and was authored by DEV Community


Print Share Comment Cite Upload Translate Updates
APA

DEV Community | Sciencx (2022-03-15T07:27:03+00:00) How I finally understood what Encapsulation is. Retrieved from https://www.scien.cx/2022/03/15/how-i-finally-understood-what-encapsulation-is/

MLA
" » How I finally understood what Encapsulation is." DEV Community | Sciencx - Tuesday March 15, 2022, https://www.scien.cx/2022/03/15/how-i-finally-understood-what-encapsulation-is/
HARVARD
DEV Community | Sciencx Tuesday March 15, 2022 » How I finally understood what Encapsulation is., viewed ,<https://www.scien.cx/2022/03/15/how-i-finally-understood-what-encapsulation-is/>
VANCOUVER
DEV Community | Sciencx - » How I finally understood what Encapsulation is. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/03/15/how-i-finally-understood-what-encapsulation-is/
CHICAGO
" » How I finally understood what Encapsulation is." DEV Community | Sciencx - Accessed . https://www.scien.cx/2022/03/15/how-i-finally-understood-what-encapsulation-is/
IEEE
" » How I finally understood what Encapsulation is." DEV Community | Sciencx [Online]. Available: https://www.scien.cx/2022/03/15/how-i-finally-understood-what-encapsulation-is/. [Accessed: ]
rf:citation
» How I finally understood what Encapsulation is | DEV Community | Sciencx | https://www.scien.cx/2022/03/15/how-i-finally-understood-what-encapsulation-is/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.