Monday, February 02, 2004

About Methods

Even 20 to 25 lines is a bit long. There are many reasons that your average method size should be considerably smaller. One to twelve lines is a better goal.

Some benefits (these are a few off the top of my head):

Maintenance costs. The longer a method, the more it will take you to figure out what it does, and where your modifications need to go.
Code readability. After the initial learning curve, smaller methods make it far easier to understand what a class does.
Reuse potential. If you break down methods into smaller components, you can start to recognize common abstractions in your code. You can minimize the overall amount of code dramatically by reusing these common methods.
Subclassing potential. The longer a method is, the more difficult it will be to create effective subclasses that use the method.
Naming. It's easier to come up with appropriate names for smaller methods that do one thing.
Performance profiling. If you have performance issues, a system with composed methods makes it easier to spot the performance bottlenecks.
Flexibility. Smaller methods make it easier to refactor (and to recognize design flaws, such as feature envy).
Coding quality. It's easier to spot dumb mistakes if you break larger methods into smaller ones.
Minimizes the need for comments. While comments can be valuable, most are unnecessary and can be eliminated by prudent renaming and restructuring. Comments that restate what the code says are unnecessary.

Downsides (maybe):

Initially it's harder to work with code with lots of methods. Over time, however, you will see well-composed code as having greater clarity.


Performance. You rarely create performance problems with more methods. If you do, it's very easy to inline methods. The rule of performance is always: make it run, make it right (e.g. small methods), make it fast (optimize).


It's difficult to do, but you can go too far. Make sure each method has a valid reason for existing; otherwise inline it.