Priciple of least knowledge :
When you are designing a system, for any object be careful of the number of classes it interacts with and also how it interacts with those classes. Also known as law of Demeter(LoD).
This principle prevents us from creating designs that have a large number of classes coupled together so that changes in one part of the system cascade to other parts. when you build a lot of dependencies between many classes, you are building a fragile system that is costly to maintain and complex for others to understand.
How to implement this design priciple?
Take any object. Now from any method in that object, we should only invoke methods that belong to
1. The Object itself
2. Objects passed in as a parameter to the methods
3. Any object that method creates and instantiates.
4. Any components of objects. (Has-A relationship)
5. A global variable, accessible by O, in the scope of M
In particular, an object should avoid invoking methods of a member object returned by another method. For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". That is, the code a.b.Method()
breaks the law where a.Method()
does not. As a simple example, when one wants to walk a dog, it would be folly to command the dog's legs to walk directly; instead one commands the dog and lets it take care of its own legs.(excellent explanation!)
Related design patterns:
Adapter pattern, facade pattern, 3-layers pattern(presentation, BLL, DAL).