I have the following class diagram:
Then I have this pseudocode in java where it is clear that the "customer" class in the getTotalCost() function does not comply with the law of demeter...
public class Customer
{
private String id;
private String name;
private String email;
private Boolean subscribed;
private ReasonType reasonUnsubscribed;
private List<Move> moves;
public Real getTotalCost()
{
Real total = 0;
foreach (Move m in moves)
{
List<Item> items = m.getItems();
foreach (Item i in items)
{
total += i.getPrice();
}
Company c = m.getCompany();
total += m.getDistance() * c.getPriceKM();
if(typeof(m)==MultipleDayMove) {
Integer extraDays = m.getEndDate() - m.getStartDate();
total += extraDays * m.getExtraPerDay();
}
}
return total;
}
}
My question is how we should change the classes so that this customer method complies with the law of demeter.
The other classes involved are like this:
Item class
public class Item
{
private Integer id;
private String name;
private ItemType itemType;
private Real price;
private Boolean assembly
public Real getPrice()
{
return price;
}
}
And finally the Company class
public class Company
{
private String taxID;
private String name;
private Real priceKM;
private Real operatorCommission;
private List<Operator> operators;
private List<Move> moves;
public Real getPriceKM()
{
return priceKM;
}
}
The law of demeter is not fulfilled in getTotalCost of Customer, I must modify something in the classes so that it is fulfilled,
Indeed, what is noticeable with your design is that the class
MultipleDayMove
is tightly coupled, the same is true withItem
.A good first principle is that generally if we find a
instance of
mistrust of our inheritance mechanisms, this will be the first thing we correct.Later we take the calculations to the directly responsible class that is
Move
.And now our Customer class will be left with the advantages mentioned in the original Law of Demeter article :
Modifications made in the future will be easier to carry out
Simplifies program complexity by giving the programmer fewer entities to consider