First you need to understand what the problem is when one object puts its insides outward, after which it becomes clear when this is not a problem.
Encapsulation and information hiding is intended to simplify development. Good design allows you to focus on the minimum number of concepts at one point in time and limit the number of changes to the minimum number of modules in case of changing requirements.
When an object exposes its insides outward, this can lead to a more fragile solution. By its nature, an open class interface should be more stable, and implementation details hidden from its clients. In this case, the implementation can be replaced without disturbing the customers.
When implementation details are leaked into an open interface, in the form of open fields or even properties, this limits the ability of the class author to change. The code of the form ABCDEFoo()
has low stability, since making changes to one of the 5 classes will probably break it.
On the other hand, not every open property reveals implementation details. Sometimes, these properties are part of the essence of the problem being solved. For example, a square has coordinates and a reversal of the form: square.Position.X
may well be justified.
Sometimes, you have to break this rule for another reason, for example, when developing libraries.
Any complex system is hierarchical, and we just need to group related concepts. The same System.out
from the Java world is a similar example. We want to combine all system operations behind a certain facade, which will be a convenient entry point for research. In this regard, we are not going to move out
to another class, and we definitely will not duplicate operations from PrintStream
in the System
class.
So, as a conclusion: the law of Demeter is not violated if the whole-part relationship is part of the subject area. The law of Demeter is not violated in the case of facade classes, the only task of which is to provide access to some objects.
But the law of Demeter is violated if the exhibited property is an implementation detail that may change in the future.