Requirement of encapsulation

132 Views Asked by At

"Encapsulation is one of the most important features of OOP and is used for data protection" according to many books and websites. Wikipedia similarly states,

Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them.

But protection from what? Is it from our own ignorant selves, ensuring we dont mess up later on when programs are too long or some other factor?

3

There are 3 best solutions below

0
Hovercraft Full Of Eels On BEST ANSWER

One of the motivations behind encapsulation and "information hiding" is to reduce coupling and thus reduce complexity, cyclomatic complexity to be precise, which in larger programs, can increase exponentially, and more complexity means a greater risk of bugs. By preventing side-effects from exposed fields, you reduce the likelihood of creating bugs.

0
epap On

Basically, you encapsulate data to protect it from everything that shouldn't modify it. Think about a private class in Java for example, with getters and setters. This is basic encapsulation, as you only allow to read and modify your data in a given way, while protecting it from any unwanted or unexpected modifications.

5
Matt Timmermans On

If you make something available, then someone's going to use it, and if someone uses it, then you can't change it. Or at least you can't change it without finding, thoroughly understanding, and testing all the stuff that uses it.

If something is privately encapsulated, you only need to worry about things in the encapsulating scope, which should be small enough to understand much more easily.