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

5

31

I came across different interview where question was asked to me why encapsulation is used? Whose requirement actually is encapsulation? Is it for users of program? Or is it for co-workers? Or is it to protect code from hackers?

Gandhiism answered 18/8, 2013 at 15:54 Comment(13)
It's the last one. Popular memory corruption attacks can only access "public" data members, so it's customary to declare sensitive fields as "protected", and for cryptography you should declare keys as "private" (so-called "private-key infrastructure"). I think. (Unless I'm getting my facts wrong...)Seem
@SLaks: Apologies in that case.Seem
Have you tried googling it? Here's a start en.wikipedia.org/wiki/…Luisaluise
@Slaks except "I think".Stipe
Encapsulation, has been around, (and valuable), since before the internet.Executive
It's not the real KerrekSB, I don't believe it... :DSelfexistent
@SLaks I believe KerrekSB was making an encapsulation joke. It made me laugh,anyway.Francklin
Ask your intervewer in next time: why python have not private fields. May be encapsulation is not important. Or encapsulation is not only private.Leontine
@Leontine python does privacy by convention. You can access anything, but you know you shouldn't. I am not sure if it is a good thing.Francklin
@juanchopanza: Python is a very high level scripting language, a lot of the low-level theory doesn't apply. You can override the standard behaviour of a property and make it do whatever (including emulating class-private behaviour) whenever you want, so compiletime visibility doesn't really fit so well.Hera
either this is a very well-played joke on @KerrekSB's part, or he's on something...Shainashaine
@Mehrdad Did you consider that it could be both? ;)Monah
@AndrewBarber: lol, admittedly not =PShainashaine
A
48

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.

Azriel answered 18/8, 2013 at 16:3 Comment(4)
This answer talks about Abstraction, not Encapsulation.Anthracoid
@Anthracoid The question is what's it for. Obviously it's not for the sake of itself, that's why I'm explaining what's it for, not what it is. And abstraction, as you've correctly noted, is what's it for.Azriel
But encapsulation and abstraction are two different concepts. At least from what I understand.Anthracoid
@Anthracoid I'm not saying they are the same. I'm saying that the second one is the benefit of having the first one. And that the first one is one of possible means to have the second.Azriel
A
25

At least in most OO languages, encapsulation is roughly equivalent to the lock on the door of a bathroom.

It's not intended to keep anybody out if they really insist on entering.

It is intended as a courtesy to let people know that entering will lead mostly to:

  1. embarrassment, and
  2. a stinking mess.
Angelangela answered 18/8, 2013 at 16:16 Comment(0)
N
24

Encapsulation prevents people who work on your code from making mistakes, by making sure that they only access things they're supposed to access.

Niedersachsen answered 18/8, 2013 at 15:58 Comment(4)
can you give me some example which can explain it more ? by text book definition of encapsulation i don't get it how it can prevent people who work on my code from making mistakes?Gandhiism
@MShahzad: Because they'll get a compiler error if they access a private field.Niedersachsen
While it may be true, it's not a key advantage given by encapsulation. There are lots of possible ways to make a mistake and thinking that encapsulation helps you with that is a bit naive. As vlastachu correctly noted - consider Python for example.Azriel
Better wording: "access modifiers prevent people on your code from mistakenly breaking encapsulation". Bartos's answer does a far better job of answering why you want encapsulation in the first place. And as M Shahzad alludes to, they do nothing to prevent any other sort of mistake.Hyperaesthesia
H
17

Encapsulation allows you to formalize your interfaces, separating levels of abstraction (i.e. "application logic accesses IO code only in this and this way").

This in turn, allows you to change the implementation of a module (the data and algorithms inside the module) without changing the interface (and affecting client code).

This ability to modify modules independently of each other, improves your ability to measure your performance and make predictions in a project's deadlines.

It also allows you to test modules separately and reuse them in other projects (because encapsulation also lowers inter-dependencies and improves modularity of your code).

Not enforcing encapsulation tends to lead to a project's failure (the problem grows with the complexity of the project).

Hulky answered 18/8, 2013 at 16:3 Comment(0)
O
7

I architected a fast-track project. Encapsulation reduces the propagation of change through the system. Changes cost time and money.

When code is not encapsulated, a person has to search many files to find where to make the change(s). Adversely, there is the question of "Did I find all the places?" and the other point "what effect to the entire system to do all of these scatter changes have?"

I'm working on an embedded medical device and quality is imperative. Also, all changes must be documented, reviewed, unit tested and finally a system test performed. By using encapsulation, we can reduce the number of changes and their locality, reducing the number of files that must be retested.

Obscurant answered 18/8, 2013 at 17:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.