| Exploring Solution Spaces © Copyright 2003-2006, by C. Keith Ray | ||||||||||||||||||||||||
|
Archives
Subscribe |
2006.Mar.13 Mon
Reading Short Methods and Small Classes
How to read short methods and small classes. 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:
|
|||||||||||||||||||||||