Clean Code and Train Wrecks

Sombrero Galaxy is depicted on the front of "Clean Code", by Robert Martin
Cover art of Clean Code (Credit to NASA and The Hubble Heritage Team)

I’ve been given Clean Code, by Robert C. Martin to read as part of my training before I start work next week. Overall, I feel like I’ve been learning a lot. In particular aspects of code I understood, but not well enough. That usually comes of listening to a person who has spent their full time job thinking about these ideas, and is able to describe them well.

There’s a few ideas that he has though which I don’t feel he should be saying are entirely correct. I might pick out one or two and make individual blog posts about them as I find time.

Train Wrecks

Chapter 6, on Objects and Data Structures, discusses what Robert calls “train wrecks” but within jQuery circles gets called “chaining”. And I think it’s one of the most beautiful parts of the syntax.

It’s how we build sentences in real life. We’d say “get all of #nav_ul’s list items, and hide them”. One sentence, that’s easily readable (and self documenting) in one line. It’s a very quick activity, that probably isn’t the main purpose of the function, so why shouldn’t the nuances of it be hidden away?


Robert would have split our sentences into shorter, more explicit sentences. “You know that list item? Yes, #nav_ul lets call it nav_ul. Well, it has a bunch of children which are lists. Yup, lets call them nav_ul_children. Hide each item within nav_ul_children.”

nav_ul = $('#nav_ul');
nav_ul_children = nav_ul.children('li');

delete nav_ul_children;
delete nav_ul;

A lot more of a mouthful… You also lose a lot of the assumed information; although it doesn’t look like it, nav_ul is actually a jQuery object. We usually instantly know that when we see one because of the distinctive $(), but if we assign it to a variable, we lose that. This is a chunk of code I would expect to be commented, so it’s lost its self documenting ability.

Robert is talking about more OO practices, specifically the Law of Demeter, which might not actually apply so strictly to a language like JavaScript where this type of chaining is typical. But I think the analogy can be done using Ruby too.

I agree though, that if you are chaining heavily you need to take a step back and ask “am I relying on the internals of the objects I’m touching too much?” If the object changes the way it produces its output, will you be tripped up? In this case Demeter does need to be taken into account, and Robert is entirely correct. Remember though, if a rule is stopping you from making your application better, just ignore it.