| > [I use] additional variables for clarity, because the names can show what you're thinking as you do the computations involved in a complex expression For me this was one of the greatest lessons of Clean Code by Bob Martin, in my opinion a wonderful book which completely changed and dramatically improved the way I write code. By improvement I mean simply the ease with which I can understand and modify my own code months after writing it/ seeing it last. There's a slight contradiction here with another great lesson of that book though which is short code (by lines) > longer code simply because it's easier to consume in a single glance. There's certainly a delicate balance at play here. It's a great thing to break down a complex process into steps, naming those steps as you go, and storing things in variables achieves that. However sometimes a better tool, and again another frequent suggestion in Clean Code (really, all credit to Bob Martin for all these ideas) is to instead break the steps into clearly-named functions, if this is possible. Chaining or nesting a series of function calls, depending on the language, can be more readable still than the variables approach and at the same time more concise. Another great tool for the belt and one of the reasons I have come to always prefer programming in a functional style vs a more stateful, OO style, where I can (even within pretty OO languages such as Java - though the lambdas in 8 have greatly improved the ease with which this can be done). |
I hate this lesson. And it's not because short code is a bad thing...when you find code that's well structured and broken down such that no method/function needs to be long, it's a joy to read. The problem comes when people learn the rule without learning the why behind it. And that leads to one logical function/method that's huge and has now been broken down into many nested methods/functions simply to satisfy the "none are long" requirement. Now, as a reader, I've still got to keep the entire context of the method/function in my head, but I now have to jump all over the code to find out what the single, large method actually does. I'd rather have a single, 200-line code block to look at than this sort of jumble.
What developers need to learn is that short methods/functions are a consequence of good techniques, not a technique in and of themselves and that long methods/functions are not bad in and of themselves, but they indicate that it's very likely that the developer hasn't put the proper thought into separating concerns and ensuring that each unit of his/her code has a single responsibility.
Sorry to get on my soapbox, but I've seen this "lesson" make ugly code even uglier when programmers don't understand the why behind the lesson.