What is encapsulation?

Encapsulation is a simple defensive programming strategy for making code bases behave predictably. It is the practice of hiding data within your class from other classes. Encapsulation allows a class to have control over how and when it’s member variables are modified.

This can be done in Java by making all the member variables private and allowing access to them only via getter and setter methods. Let’s say you have a class called “car” with a member variable called “color”. If you’ve encapsulated your “car” and another class needs to know your cars color then you would need to create a public method to access the color variable. These methods can be as simple as something like “getColor()” or you could define a method that contains logic that determines what’s returned.

If you’re new to programming then an example is in order. Let’s say you have an actual physical car. Let’s also say that you have a jacket, hat and an umbrella in your car. In this case, encapsulation is like locking the doors to your car. Your locked car isn’t inaccessible, the nature of it being locked just means that people can only get access to the things in your car in the ways you allow (your keys). When encapsulating you’d provide a way for people to get into your locked car like leaving a window cracked. The cracked window usually takes the form of a getter method.

When would you use it?

Encapsulation isn’t a practice that one would set out to implement. It’s more of a best practice that one would implement where necessary and possible as part of normal everyday programming. If you were to encounter a code base that’s unpredictable at execution and hard to troubleshoot then encapsulating would be a good starting point for creating reliable behavior.

Why is it valuable?

Like I said above encapsulation is more of a best practice. It’s valuable because the programmers that came before you had problems with unpredictable code and applied encapsulation to fix it. A more practical way of stating it’s value is that it will save you time in the long run.