How much information about one object should another object have? Should an object be able to access the inner objects of another one?
The law of Demeter
Simply put, the Law of Demeter says that an object shouldn’t have knowledge of the inner workings of another object.
A method in an object should only have access to:
- itself
- the methods parameters
- objects created inside the method
- the objects that are directly inside it
- global variables
The following examples doesn’t follow the Law of Demeter
objectA.ObjectB.Method();
This example follows the Law of Demeter
ObjectA.Method();
Why does this law exist?
It should be clear by now, that one very important goal of writing clean code is to make modifying software easier and less error prone. When objects do a good job of hiding the way they work, changing them is a lot simpler.