Breaking the "Law of Demeter" and possible solution to this issue

45 Views Asked by At

Recently I have read about the "Law of Demeter".

Let's suppose we have:

public class Restaurant {
     private String name;
     private Address address;

    // getters and setters...
}

public class Address {
     private String city;
     private String postalCode;

     // getters and setters...
}

Let's suppose somewhere else I have:

public void myFoo(Restaurant restaurant) {
     ...
     String restaurantCity = restaurant.getAddress().getCity(); // Breaking Demetra?
     ...
}

Am I breaking the Law of Demeter?

I think so because myFoo is "touching" an object (address) which is not a class attribute.

My solution is to modify as follows:

public class Restaurant {
     private String name;
     private Address address;

     // getters and setters...

     // added
     public String getCity() {
          return this.getAddress().getCity();
     }
}

public void myFoo() {
     ...
     String restaurantCity = restaurant.getCity();
     ...
}

Is that correct?

0

There are 0 best solutions below