Observer can be considered a break in encapsulation?

6

Observer uses abstraction and interfaces . Let's suppose that a Observer "watches" the changes of state of certain classe and informs them to another external agent, we can consider this a break of encapsulation, since an external agent has access to these changes of state? p>     

asked by anonymous 15.09.2016 / 16:25

1 answer

7

Some people think so, in a sense. This can be seen in a excellent response in OS . But not in the direction of the question here.

At least what is described in the SO linked answer above is the opposite of the one asked here. It breaks consumer encapsulation, the class that signs a notification is that it exposes what it should not to whom it wishes to observe. It even causes memory leakage problems if you are not sure what you are doing. But that's another problem.

This problem could be solved without abandoning the default. The problem is not the standard, it is the solution adopted. This can be seen in another question in SO .

Other problems

Certainly you have bigger problems. The same answer shows some. Another answer there in SO describes another problem. There are those who see more problem and propose a solution with another standard .

Note that this has more to do with coupling than encapsulation. And maybe the coupling problem has more to do with the question here.

The encapsulation break occurs only when an implementation detail is exposed. And that's why this concept is useful.

It's not enough to be a problem

The question is whether this is so important. The fact is that this pattern has been used without major problems for quite some time. Academics will find problems, will stick to the smallest details. Engineers will accept that everything is not perfect and if it works properly without causing critical problems it can be used normally.

Some confusion

The default does not necessarily have to use interfaces.

He does not need to observe change of state, that is a possibility. It looks at some action, the change of state is just the most common.

Within what is in the question I would question: is a getAlgumaCoisa() method that catches a state is encapsulation breaking? An agent outside the class has access to the state. Can not? Or the problem is just watching the change of state? If so, what would be the solution? I do not know. Even if you use another pattern, you still have that access. The premise of the question does not make much sense.

    
15.09.2016 / 17:23