Saturday, May 7, 2011

Clean Code Review

Today I read most of Clean Code by Bob Martin. The forward describes the book as being divided into 3 sections: guidelines, case studies, and "code smells" (negative heuristics). It also clearly cautions again reading sections 1 and 3 and skipping 2. Clearly, I went ahead and did just that. If that invalidates any of my review, so be it. I felt it was valuable nonetheless.

One of this main tenets, which I find myself agreeing with, is that functions and classes should be small. And then they should be smaller. While it sounds silly, I think applied consistently and combined with great identifiers, it can make code really simple to read.

For example, he recommends against nested scopes inside functions. This means that while, if, and fors should consist only of a single line, which is either a statement, or a function call. Great names for these functions leave little surprise about what they do, and the contents are basically what you would expect.

This interplays nicely with the principle he espouses of only stepping down 1 level of abstraction in a function call. Each function can deal with a single responsibility by stepping down 1 level of abstraction and perform a few simple non-nested steps. Any more complication, or deeper layers of stepping, requiring extracting another function.

One benefit of all this function extracting, which I hadn't thought of before, is that it is fruitful ground for extracting classes. Suppose you have a longish function that performs a sequence of steps on some local data. You extract those steps out into methods and make the local data instance variables. The original function now calls the extracted methods.

However, you now have a little wad of instance data which is accessed only by a few methods. This is perfect ground for extracting a new class and moving those methods to it. I've used this a few times in my own code without really thinking about it, and been really pleased with the results.

Overall it's really nice book, and a very fast read (especially if you skip the case studies). While the author is clearly a heavy Java developer, I still felt like I got good insight out of it, and I am definitely not a big Java guy.

1 comment:

  1. Your book reviews have convinced me to buy both Clean Code and The Passionate Programmer. Thanks! I'll let you know what I think.

    ReplyDelete