The Law of Demeter aims to remove navigation trains (dot counting), and it also aims to provide good encapsulation with loosely coupled code.
A method that understands a navigation train breaks the Law of Demeter. For example, have a look at the following code:
report.Database.Connection.Open(); // Breaks the Law of Demeter.
Each unit of code should have a limited amount of knowledge. That knowledge should only be of relevant code that is closely related. With the Law of Demeter, you must tell and not ask. Using this law, you may only call methods of objects that are one or more of the following:
- Passed as arguments
- Created locally
- Instance variables
- Globals
Implementing the Law of Demeter can be difficult, but there are advantages to telling rather than asking. One such benefit is the decoupling of your code.
It is good to see a bad example that breaks the Law...