Law of Demeter
Overview
Most time when we plan to upscale our application or maintain some features, we end up building it from scratch all over again. This is because any change or adding we would want to make will run across the entire codebase. This kind of codebase is not following the law of Demeter.
What is the Law of Demeter?
The Law of Demeter principle reduces dependencies and helps build components that are loosely coupled for code reuse, easier maintenance, and testability. This principle states that an object should never know the internal details of other objects. It was designed to promote loose coupling in software designs. LoD tells us that it is a bad idea for single functions to know the entire navigation structure of the system.
Below is a demonstration of LoD as give by @arunsasidharan
Law of Demeter violated
Law of Demeter observed
In conclusion, Following this rule is very hard. Hence it is even been called as the Suggestion of Demeter because it’s so easy to violate. But the benefits are obvious, any function that follows this rule, any function that “tells” instead of “asks” is decoupled from its surroundings.
What Do I mean By “Tells” Instead of “Asks”
Tell, Don’t Ask Principle states that instead of asking an object a question about it’s state, making a decision, and proceeding forward we should strive to tell an object what to do.
Example of Ask
def street_name(user)
if user.address
user.address.street_name
else
'No street name on file'
end
end
Example of Tell
def street_name(user)
user.address.street_name
end
class User
def address
@address || NullAddress.new
end
end
class NullAddress
def street_name
'No street name on file'
end
end
Reference
object-oriented-tricks-2-law-of-demeter