Why encapsulation is an important feature of OOP languages? [closed]

Encapsulation helps in isolating implementation details from the behavior exposed to clients of a class (other classes/functions that are using this class), and gives you more control over coupling in your code. Consider this example, similar to the one in Robert Martin’s book Clean Code:

public class Car
{
//...
public float GetFuelPercentage() { /* ... */ };

//...

private float gasoline;
//...
}

Note that the client using the function which gives you the amount of fuel in the car doesn’t care what type of fuel does the car use. This abstraction separates the concern (Amount of fuel) from unimportant (in this context) detail: whether it is gas, oil or anything else.

The second thing is that author of the class is free to do anything they want with the internals of the class, for example changing gasoline to oil, and other things, as long as they don’t change its behaviour. This is thanks to the fact, that they can be sure that no one depends on these details, because they are private. The fewer dependencies there are in the code the more flexible and easier to maintain it is.

One other thing, correctly noted in the underrated answer by utnapistim: low coupling also helps in testing the code, and maintaining those tests. The less complicated class’s interface is, the easier to test it. Without encapsulation, with everything exposed it would be hard to comprehend what to test and how.

To reiterate some discussions in the comments:

  • No, encapsulation is not the most important thing in OOP. I’d dare even to say that it’s not very important. Important things are these encouraged by encapsulation – like loose coupling. But it is not essential – a careful developer can maintain loose coupling without encapsulating variables etc. As pointed out by vlastachu, Python is a good example of a language which does not have mechanisms to enforce encapsulation, yet it is still feasible for OOP.

  • No, hiding your fields behind accessors is not encapsulation. If the only thing you’ve done is write “private” in front of variables and then mindlessly provide get/set pair for each of them, then in fact they are not encapsulated. Someone in a distant place in code can still meddle with internals of your class, and can still depend on them (well, it is of course a bit better that they depend on a method, not on a field).

  • No, encapsulation’s primary goal is not to avoid mistakes. Primary goals are at least similar to those listed above, and thinking that encapsulation will defend you from making mistakes is naive. There are just lots of other ways to make a mistake beside altering a private variable. And altering a private variable is not so hard to find and fix. Again – Python is a good example for sake of this argument, as it can have encapsulation without enforcing it.

Leave a Comment