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?
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.