Law of demeter says that an object can't invoke a method M from an object B from an object A. But is it aplied to properties too? Example?
public class B{
public bool IsValid();
}
public class A{
public B B{get;set;}
}
Can I do something like that?
var isValid = new A().B.IsValid()
or should I do this:
public class B{
public bool IsValid();
}
public class A{
private B B{get;set;}
public bool IsValid(){
return B.IsValid();
}
}
var result = new A().IsValid();
Is there a problem(according to law) if I access a B's method from A?
The Law of Demeter principle reduces dependencies and helps build components that are loose coupled for code reuse, easier maintenance, and testability. The Law of Demeter (or the Principle of Least Knowledge) is a design guideline for developing software applications.
Demeter's law is known as “don't talk to strangers” because: Each unit should have only limited knowledge about other units — only units “closely” related to the current unit. Each unit should only talk to its friends — don't talk to strangers. Only talk to your immediate friends.
The Law of Demeter asks us to minimize coupling between classes and avoid reaching out to the third object in order in order to make refactoring and developing new features easily.
It is so named for its origin in the Demeter Project, an adaptive programming and aspect-oriented programming effort. The project was named in honor of Demeter, “distribution-mother” and the Greek goddess of agriculture, to signify a bottom-up philosophy of programming which is also embodied in the law itself.
Yes, it applies to properties as well, since the client of this code:
var isValid = new A().B.IsValid();
is coupled to A
and also to B
.
When fixing the law of Demeter violations, you have to balance the need for decoupling and the need to keep responsibilities clearly separated. Sometimes you can create Demeter transmogrifiers: classes that have too many unrelated methods just to comply with the law of Demeter.
Update: An example of a Demeter transmogrifier can be found in this post:
Consider, for example, someone who’s trying to kiss up to his boss:
sendFlowers(john.getManager().getSpouse())
. Applying Hide Delegate here would yield agetManagersSpouse()
method in Employee. Yuck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With