Use one dot per line.
Three against one
Reasons to follow this advice:
- A line is easier to read
- You immediately know what caused a null error
- It avoids coupling
Reasons to not follow this advice:
- Being too lazy.
Easier to read
Compare the line
That’s just the point about the single line, but even in total it’s easier to grasp what’s happening if we “dig out” our variables beforehand:
Bar bar = foo.Bar; Id id = baz.Id; bar.GetInfo(id);
Knowing the null
In the first example, if you get a null error, it could be
foo, it could be
bar or it could be
baz. If the error is not immediately clear from the context (and when is it ever), you’ll have to add some debugging to the situation and then you’ll have to run it again… before you can even start to investigate why that value was null.
In the second version, the error line number immediately tells you which value was null.
You might have an aversion to turning a line like
result = foo.Bar.Baz.Tower.Dog.Crocodile;
Bar bar = foo.Bar; Baz baz = bar.Baz; Tower tower = baz.Tower; Dog dog = tower.Dog; result = dog.Crocodile;
That’s 4 lines more! And it seems a bit confusing…
Well, that’s because you have to take 5 steps before you get what you want. That’s not an issue with this advice, that’s an issue about the code structure. Putting it all in one line is just hiding the symptom.
If you access
foo.Bar.Baz.Tower.Dog.Crocodile, then this code relies on
foo having a
bar, which has a
baz, which has a
Tower, which has a
Dog, which has a
Crocodile. That’s a lot of assumptions this code makes, and that’s a lot of mind-overhead for a programmer who would probably rather think about the problem at hand instead of 5 indirections.
Next Article: Make an Effort to Name Things