Encapsulation violation in oops.

Background –

First of all, let us understand the meaning of encapsulation. In design terminology, we call any module a box. It could be a black box, or a white box, or a gray box. Depending on its implementation. If you are very new in designing. Please read about the block box from this link. Other modules should not have any access to any private implementation/logic of this module and vice versa.

Let’s understand it through an example. Praveen is an excellent cryptography programmer. And I am in need to implement cryptography in my module. There are two ways to implement cryptography here. First, I ask Praveen to show me how he writes cryptography code and learn from that and implement it on my own. Second, I tell Praveen to give me an executable (or library) implemented by him. So that I can use that library and complete my module.

Here Praveen should not let me know how he write cryptography program. If he does so, I may implement it on my own and modify his code. That is called encapsulation violation.
Any module or a black box is not supposed to show its non-public property or methods/implementation to the outer world. If it does for any reason, then it’s called encapsulation violation.

Definition -

“A condition where any object can see internal non-public state or implementation of other object, then we call this condition – encapsulation violation.” It’s dangerous, it can harm the existence of another object. Also, it can increase coupling between two modules.

If we don’t use association in the right way, then it could lead us encapsulation violation.
You cannot blame other object for knowing the internal state of your class’s object. As you only permitted encapsulation violation through corrupt code practices or sometimes purposefully.

When to share internal state (or/and implementation) with other object?

Sometimes there is a need to share some information with an external system. For example, in the visitor design pattern, or in iteration design pattern. So, in this case - when an object is forced to share its private information, please use Implicit and explicit trusting to implement your code.


Thanks for reading it. To learn more about design patterns and basic design principles, please see my web page.

Comments

Post a Comment

Popular posts from this blog

Non-virtual interface idiom (NVI)

Factory method design pattern for beginners.

Architectural patterns => Mud to structure => layers.