Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is law of demeter aplied to properties too?

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?

like image 662
MuriloKunze Avatar asked Dec 22 '12 21:12

MuriloKunze


People also ask

What is the Law of Demeter attempting to achieve?

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.

How do I follow the Law of Demeter?

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.

What is the Law of Demeter trying to prevent?

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.

Why is the Law of Demeter called that?

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.


1 Answers

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 a getManagersSpouse() method in Employee. Yuck.

like image 73
Jordão Avatar answered Oct 21 '22 01:10

Jordão