To manage complexity, one idea is that a class should be designed so that it does not need to know about and depend upon almost every other class in the system. By limiting which classes communicate with each other, you can enforce the principle of Least Knowledge. This principle is also realized in a rule known as The Law of Demeter.
The underlying idea of this Law is that classes should know about and interact with as few other classes as possible. This means that any class should only communicate with its “immediate friends”. These “friends” would be other classes that one class should only know about. It helps to reduce coupling and provide stability to a system.
- A method, M, is an object, O, can call on any other method within O itself (encapsulated within the same object).
- A method M, can call the methods of any parameter P (encapsulated within an object that is in the parameters of M).
- A method M, can call a method, N, of an object, I, if I is instantiated within M (encapsulated within an object that is instantiated inside of M).
- Any method, M, in object O, can invoke methods of any type of object that is a direct component of O (encapsulated within an object that is referenced in an instance variable of the class for M).
To summarize the rules, a method should not invoke methods of any object that is not local.
Classes should know as little as possible about your system as a whole, this will help to reduce amount of coupling and prevent unwanted effects from cascading through your entire system.