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:
is coupled to
Aand also toB.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: