Tuesday, September 14, 2010

Cleaner Code with One Simple Technique


Clean code bookWhat is the simplest technique you can apply to write cleaner code? Clean Code by Robert C. Martin is a very good book that focuses exclusively on writing cleaner code. I read this book several months ago and at a recent code review I was again reminded of the value of this simple technique. The simplest technique to apply for writing cleaner code is to keep functions small!



Advantages of Small Functions

  • Functions perform one specific responsibility (single responsibility principle)
  • Functions become very readable
  • Functions are more likely to descend only one level of abstraction (tip G34 from Bob's book)
  • Small functions promote reusability and help eliminate duplication
  • Your favorite IDE makes extract method so simple
  • Small functions adhere to these valuable coding principles by design


Ideal Function Size

"Continue to extract methods until you can not extract methods anymore. Extract until you drop!" This is Bob's recommendation from his online presentation of Bad Code and Craftsmanship. Personally, I couldn't agree more. For the past three months I have been following this practice and this simple technique has a high return on investment.



Additional Clean Code Tips

Looking for additional clean code tips? Chapter 17 (Smells and Heuristics) in Bob's book is a very quick read and covers sixty-six valuable coding practices. Alternatively, Bob discusses many clean code practices in his online presentation. In fact, he leads off the discussion by focusing on the importance of small functions!