This post originated from an RSS feed registered with Agile Buzz
by Keith Ray.
Original Post: Reading Short Methods and Small Classes
Feed Title: MemoRanda
Feed URL: http://homepage.mac.com/1/homepage404ErrorPage.html
Feed Description: Keith Ray's notes to be remembered on agile software development, project management, oo programming, and other topics.
When reading a Long Method, we figure out the algorithm from the implementation. For example, we see an expression, and we figure out that the line of code "i = (lowIndex + highIndex) / 2;" is computing the middle index. This long details-only style can get tiring, and tends to lead to a lot of duplicated code.
When reading a Short Method, the algorithm is obvious (if intention-revealing names are used), but we have to delve into other methods to see the implementation. For example, the line of code "i = middleIndex()" states the intent, but you would have to look at its implementation to see how it does it. This can also get tiring, if we can't trust that anything is implemented correctly and therefore feel that we must investigate every method.
One way to get the feeling that you can trust the class and method names, so you don't have to investigate each and every method, is to have extensive automated tests that verify that methods and classes are behaving correctly individually and in integrated groups. These tests can also serve as documentation -- examples of usage.
Another way to help understand short methods and small classes is to have some high-level documentation explaining their relationships. Design patterns are one way to do this. JUnit originally came with a Cook's Tour that presented the classes of JUnit in terms of design patterns: Adapter, Command, Composite, Collecting Parameter, etc.
JUnit also has very short Cookbook that tells you how to use the framework in the simplest ways. There are more sophisticated ways to use JUnit, but those are documented elsewhere. The Cookbook just has enough to get you started with the common cases.
The success of JUnit probably stems from its easy-to-read documentation as much as its simple, (mostly) decoupled, easy-to-read code.
How do you know if a function is too long? Jerry Weinberg's test for that is:
Pick a function.
Understand it, what it's supposed to do, how that is accomplished.
Memorize the function.
Then, without looking at the original code, write the function from memory.
If you've made a mistake, the function was too long, or otherwise too complex.