What 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!
What about shortcut unreadable code in Scala ?
ReplyDeleteThanks for the post. Keeping functions small seems like a good idea but it may result in a larger number of functions if taken literally. What do you think about that.
ReplyDeleteSmall methods are easier for HotSpot to inline == better performance
ReplyDelete"Thanks for the post. Keeping functions small seems like a good idea but it may result in a larger number of functions if taken literally. What do you think about that."
ReplyDeleteAfter reading the book I thought about this too. Initially, I reviewed my code with a focus on the single responsibility principle and extracted out each unique responsibility. By design, this produces relatively short methods. Actually, when I thought in terms of "extract method" it forced me to think of responsibilities. Focus on single responsibility and the function size and count should strike a good balance.
--Brad
readability is above many things but people often don't pay enough attention to it and then spend much time to understand the code while maintaining it. by the way nice post.
ReplyDeleteThanks
Javin
How HashMap works in Java