oopdesign-patternssolid-principleslaw-of-demeter

Understanding Demeter's Law


I'm trying to understand the SOLID principles behind OOP and came across with this doubt.

Class Diagram

Following the previous class diagram, I am going to calculate the base_cost for a Vehicle. For such, I need to access the horsepower and the tax and then calculate everything with the base_cost() function.

Pseudocode

From what I understood in this link I could guess that it DOES NOT violate Demeter's law since you are accessing methods from a class created locally (Vehicle). Am I right?


Solution

  • As stated in the comments, SOLID does not include the Law of Demeter. Which is a shame, because it is much more pertinent and useful than all of the SOLID suggestions. Just to get that out of the way.

    Regarding your exact case, calling methods on the vehicle is of course allowed by Demeter, because that object is held as an instance variable. There is an explicit rule for that.

    However, if we're thinking about an object-oriented system, things returned by get_price(), get_power() and get_tax() are also objects, since everything is supposed to be an object in an OO system. In Law of Demeter context, multiplying the returned values is "sending messages" to those objects. Now this is not allowed, since you don't directly hold references to those objects nor are they parameters nor created in this call.

    So, while "getting" objects/values might be technically legal according to the Law of Demeter, calling methods on those objects/values that you got are not. So basically anything that has "getters" will eventually violate the Law of Demeter.

    This is on purpose. What the Law of Demeter actually enforces is encapsulation. The idea that you don't want to "get" data out of an object, instead you want to ask the object to perform behavior using the data it has.