I started to see spots before my eyes. Huh? Let me explain.
Did you ever write code where the data in the object is five levels deep in your application? It's considered a code smell.
Why, you ask, would dots be considered a code smell?
Consider this piece of code:
var state = customer.Location.Address.State;
Now you're seeing spots.
What happens when you execute this line of code and one of your objects is null, like the Location, Address, or even quote object? Ka-Booom!
How can we protect ourselves from this line of code blowing up at runtime?
The Law Of Demeter
We can easily reduce the number of dots in the statement by following the Law of Demeter.
In programming, the Law of Demeter follows these guidelines:
A method of an object may only call methods of:
- The object itself.
- An argument of the method.
- Any object created within the method.
- Any direct properties/fields of the object.
The code above doesn't follow any of these guidelines.
If you take the code above and refactor it, it may make more sense to shorten your object hierarchy.
var state = customer.GetState();
var state = customer.Location.GetState();
This makes your code a little cleaner. Only focus on your object's immediate children, not grandchildren.
What about a Builder/Fluent pattern?
"That's all well and good, but what about a builder pattern or something that uses a fluent syntax?"
Well, as Phil Haack has mentioned in his post, this "Law" is more of a guideline. Even Martin Fowler calls it "The Occassionally Useful Suggestion of Demeter."
Is it really violating any law if it's deliberately using the dots for a builder pattern meant to create a programmatic sentence?
I guess it's the age old answer... it depends.
It's not really digging down into a hierarchy of objects, but building something in a granular manner. If additional objects were used in the builder, it would be hidden from the builder design as it was meant to.
Would it make sense to use methods to build your pattern?
Not really. It wouldn't make it fluent. You'd have a large number of methods listed instead of a one-liner to build everything.
Again... I guess it depends.
Developers are aware of the Law of Demeter, but some don't practice it. Yes, I'm guilty as well.
If you do keep this law in mind, it will add a layer of protection against bad practices. It's like saying "I want the State. Get it for me. I don't care how it happens behind the curtain, just get it for me" instead of asking every object down the object tree for the information.
One big benefit is not having every object coupled together in your system.
Do you practice the Law of Demeter? Leave us a comments.