If you've read my previous entry Coding By Intention, you know I like small methods. Small methods are easy to understand and easy to maintain - they’re small after all. The name of a small method can reveal your intent to those higher level methods using it.
Besides these obvious things, small methods remove duplication and thus provide chunks of reusable code. When I’m doing test-driven development, after I’ve coded by intention and refactored by extracting methods, I wind up with several small methods that are typically private scope in the class I’m developing. These private methods are potential candidates for reusability - reusability beyond the class I’m working with. In another blog entry, I want to go into detail on this part, but for now, I’ll give you a little teaser: these small, private methods typically belong on another object (one of the objects passed in as an argument) or maybe on a utility class.
The biggest negative is when you’re tracing through code. Maybe you’re doing a code review, debugging, or maybe just want to understand all the details. It is pretty annoying sometimes to keep drilling down in methods and then trying to remember how you got to where you are and then trying to find your way back to where you started. However, I’ll make this sacrifice to get all the benefits of reusability, algorithmic clarity, etc. that small methods provide.
Shortly afterward, I remember taking an object-oriented analysis and design course. During a break, I was discussing the method lines practice with the instructor, who said something like all methods should be 10 lines or less. At that time, I couldn’t even understand how that was possible, with exception handling, logging and all.
Today, my methods range from one line to a screenful. A screenful in my Eclipse IDE is 36 lines. Those 36 lines include the start of Javadoc to the ending bracket of the method. The one line methods are either trivial or intention revealing methods (like the notTooCold() method from my earlier blog). Admittedly, I do go over a screen from time to time. It’s most likely because I’ve been lazy. Whenever I feel a method is getting too long, I look for reusability and intention, and extract methods.
No comments:
Post a Comment