Search code examples
ooplanguage-agnosticencapsulationinformation-hiding

Requirement of encapsulation


"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?


Solution

  • 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.