Slashdot Mirror


Clean Code

Cory Foy writes "As developers, system admins, and a variety of other roles in IT, we have to deal with code on a daily basis. Sometimes it's just one-off scripts we never have to see again. Sometimes we stare at something that, for the life of us, we can't understand how it came out of a human mind (or, as the book puts it, has a high WTF/minute count). But there is a time when you find code that is a joy to use, to read and to understand. Clean Code sets out to help developers write that third kind of code through a series of essay-type chapters on a variety of topics. But does it really help?" Read below to find out. Clean Code - A Handbook of Agile Software Craftsmanship author Robert C. Martin pages 431 publisher Prentice Hall rating 10 reviewer Cory Foy ISBN 978-0-13-235088-4 summary A great book for anyone wanting to really improve how they write code I had the pleasure of attending Bob Martin (Uncle Bob)'s sessions at several agile software conferences over the past several years. In them, Bob has a unique way of showing us the value of clean code. This book is no different. There is a warning in the introduction that this is going to be hard work — this isn't a "feel good" kind of book, but one where we slog through crappy code to understand how to make it better. The authors also point out that this is their view of what clean code is all about — and fully acknowledge that readers may "violently disagree" with some of the concepts.

The book wastes no time diving in covering "Meaningful Names", "Functions" and "Comments" right in the first several chapters. While I could sum up the chapters by saying, "Use them", "Keep them small" and "Comments don't make up for bad code" it wouldn't do the wisdom in the book justice. For example, in the meaningful names chapter, he talks about making pronounceable and searchable names — staying away from things like "genymdhms" (Generation date, year, month, day, hour, minute and second) and preferring things like MAX_STUDENTS_PER_CLASS.

After touching on formatting rules (including some very interesting graphs on the file and function length distributions in some common open source projects) he dives back into some more controversial topics — "Objects and Data Structures", and "Error Handling". The Objects chapter does a great job of drawing a line in the sand between Objects and Data Structures and why it really is both important, and clearer, to keep your privates in your private classes.

The Error Handling chapter is important because of the application of earlier chapters — the Do One Thing rule. Your functions should do one thing — either handle business logic, or exception handling, but not both. It's the difference between this:

try { s = new Socket(4000); s.OpenSocket(); string data = s.ReadFromSocket(); if(data == "32") data = "42"; printer.print(data); } catch(Exception ex) { if(ex == NetworkInterruptException) { //do something } if(ex == PrinterOnFireException) { //do something } logException(ex); }

And this

try { tryToPrintDataFromSocket(); } catch(Exception ex) { logException(ex); }

We then move on to "Boundaries" and "Unit Tests" — the critical points where we tend to really let code go. If we work hard, usually we can keep our own code clean. It's when we have to begin interacting with other systems that things start to go astray. In these chapters, Bob and James Grenning show us how to keep our code at the boundaries clean — and how to keep our code working, period. The authors are proponents of Test-Driven Development, and the chapter on unit tests is a fresh reminder that those tests are just as much code, and need to be kept just as clean as any other code we write.

We then begin to move at a higher level, starting with "Classes" and "Systems". The classes section should be familiar to most any OO programmer — keep the classes small, with a single responsibility, and low coupling. He also talks about Organizing for Change which is a great section on how to structure classes in a way that keeps them open to change. The Systems section continues along the path with the great reminder to "Separate Constructing a System from Using It". Here they go into Dependency Injection and Aspect-Oriented Programming, which I'll address in a bit.

Moving even higher up the chain, the book then tackles "Emergent Design". The key is to keep the design simple, which according to Kent Beck, means:
  • Runs all the tests
  • Contains no duplication
  • Expresses the intent of the programmer
  • Minimizes the number of classes and methods

With the above list given in order of importance. Really this breaks out to "Runs all the Tests" and "Refactoring" or making the code better. Simple design is perhaps one of the harder things out there, and yet the most important. When you look at systems that highly scale, it's because they are made up of simply designed components which work very well together.

After the Emergent Design chapter there is suddenly a chapter on Concurrency. This was not something I expected to see, but was very glad to. Too many times books about patterns and design don't address problems like scaling and concurrency. But this chapter does a great job of introducing the necessary steps that need to be taken to deal with concurrency — while still keeping your code clean. The book also provides an appendix which goes even deeper into the concurrency topic which I found to be quite good. Both this chapter and the appendix provide some very valuable rules that I personally have used when writing concurrent systems — like "Get your nonthreaded code working first" and "Run with more threads than processors" to flush out problems.

Chapters 14-16 cover the cleaning up of three different sections of code — an argument processor, JUnit and SerialDate, which is part of the org.jfree package. These chapters really hold true to the warning in the introduction that we'd be going through some code. However, the refinements work very well, and I think that each of them show the value of how much cleaning up the code can improve the readability of even code that works well and seems clean.

The last chapter is a "Smells and Heuristics" chapter which I'm finding to be a handy reference guide for code smells I see. When something is bothering me with code I'm reading, I flip to this section first to see if they have it listed. And with things like "Replace Magic Numbers with Named Constants" you can be sure that all of the advice that should have been beaten into your head long ago is still there, and relevant.

All in all I think this is a very valuable book for any developer wanting to improve how they write code. For senior level people, some things may seem trivial, but if you really take the time to look at the structural changes being made and apply them, you will write better code. For functional developers — the authors believe in OO, but there are still valuable nuggets that are applicable outside of that (like "Use Copies of Data" in the concurrency section). And for any developer, the insights are really good, and you'll find yourself writing down little snippets to hang on the wall.

The challenges with the book are first that it is just as they said — hard work. This is not a flip-through-with-your-mind-shut-off type book. If you want the most out of it, you have to be willing to really work at it. The other challenges are that at times it gets way too Java-centric. All of the code examples being in Java is fine, but some of the chapters (most notably the Systems chapter) really go heavy into Java tools and the Java way which, to me, weren't always applicable across languages.

All in all, I'd highly recommend this book to anyone wanting to improve how they write code. You likely will find yourself violently disagreeing with parts, but the total sum more than makes up for it.

You can purchase Clean Code - A Handbook of Agile Software Craftsmanship from amazon.com. Slashdot welcomes readers' book reviews — to see your own review here, read the book review guidelines, then visit the submission page.

8 of 214 comments (clear)

  1. Run with more threads than processors by nwf · · Score: 5, Insightful

    Run with more threads than processors

    Funny, I've found more problems by running with fewer threads than processors. Otherwise, you aren't necessarily getting true concurrency. Running ten threads on a single processor isn't going to help you find some of the pesky concurrency issues that arise from true parallel execution. Of course, one should run with more threads than processors to test that as well.

    Either way, writing non-trivial parallel code isn't easy.

    --
    I don't know, but it works for me.
  2. Clean Code by codepunk · · Score: 4, Insightful

    I recently ran across a situation where I looked a piece of code someone else wrote and thought to myself that
    is really ugly. I set out to write a clean version but gave up when I figured out that no matter what I did
    this was still going to be ugly. Not so much because of a poor job coding it but because of what the code had
    to actually perform.....I guess it is just not possible to always put lipstick on the pig.

    --


    Got Code?
  3. Re:Is the problem one of craft or mentality? by dubl-u · · Score: 5, Insightful

    Put another way, the kind of engineer that would actually benefit from a book like this, has probably already read a book like this.

    I think you've created a false dichotomy.

    I haven't read this book yet (although Bob Martin's other stuff is great), but back at the dawn of time, I was working with a team that was all relatively young. When McConnell's "Code Complete" came out, we all went through it pretty excitedly.

    Although we had the right spirit, and we each could have named some of the things in the book, none of us could have articulated all of them. And there were a lot of subtleties that we had never thought of.

    So I'd agree that jerks won't read this and nice graybeards don't need to, there are plenty of people who are perfectly nice that haven't perfected their craft yet. They can use this book.

  4. Re:Depends on function by Nerdfest · · Score: 4, Insightful

    It's taken me a long time to get myself out of this mindset. I used to always go for the absolute fastest implementation I could come up with. I now generally go with 'fast enough' rather than 'as fast as possible' if the latter is more maintainable. Sometimes the bar for 'fast enough' lowers, but not often.

  5. Re:Depends on function by dubl-u · · Score: 4, Insightful

    related code" [sic] are NOT opposites. In fact, I have seen a huge number of situations where I sped something up by cleaning out the code.

    I know what you mean, but the guy has a point. I have also often sped things up by removing "performance improvements" that some dolt had added because he thought he was being clever.

    My view, which I guess you'd agree with, is that it's best to start with clean, simple code. Usually, that's plenty fast. If performance tests prove that you have a problem, and a profiler shows you the source of the problem, only then should you sacrifice clarity for speed. And you should only do just enough to meet your performance goals.

  6. Re:yay! by Surt · · Score: 4, Insightful

    And if he had documented his code, explaining the performance advantages, you'd have read it in an hour and reached the same goal, and he wouldn't have dozens of WTFs to his credit.

    --
    "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
  7. Re:Depends on function by Anonymous Coward · · Score: 5, Insightful

    Bzzt, fail, please go buy the book.

    http://en.wikipedia.org/wiki/Optimization_(computer_science)#Quotes

    Clean code is efficient and performs well because you can easily see where the issues are and optimise there appropriately.

  8. Re:I really want a copy of this... by Eudial · · Score: 4, Insightful

    There are naturally various considerations: Value caching as you mention, whether the programming language optimizes tail recursion, and so forth.

    But the real shenanigans in the function is that you can use mathematics and find that the sum of the series 1...n is n*(n+1)/2 straight away, so making such a function is a moot exercise altogether.

    On the other hand, keeping that sort of mathematics arcane and shrouded in mystery creates thousands of extra programming jobs all across the world.

    --
    GAAH! MY PRINTER IS ON FIRE!!! PUT IT OUT! PUT IT OUT!