Long Method

Prev don't be afraid of buying books Next

In their description of this smell, Fowler and Beck [F] explain several good reasons why short methods are superior to long methods. A principal reason involves the sharing of logic. Two long methods may very well contain duplicated code. Yet if you break those methods into smaller ones, you can often find ways for them to share logic.

Fowler and Beck also describe how small methods help explain code. If you don't understand what a chunk of code does and you extract that code to a small, well-named method, it will be easier to understand the original code. Systems that have a majority of small methods tend to be easier to extend and maintain because they're easier to understand and contain less duplication.

What is the preferred size of small methods? I would say ten lines of code or fewer, with the majority of your methods using one to five lines of code. If you make the vast majority of a system's methods small, you can have a few methods that are larger, as long as they are simple to understand and don't contain duplication.

Some programmers choose not to write small methods because they fear the performance costs associated with chaining calls to many small methods. This is an unfortunate choice for several reasons. First, good designers don't prematurely optimize code. Second, chaining together small method calls often costs very little in performance—a fact you can confirm by using a profiler. Third, if you do happen to experience performance problems, you can often refactor to improve performance without having to give up your small methods.

When I'm faced with a long method, one of my first impulses is to break it down into a Composed Method [Beck, SBPP] by applying the refactoring Compose Method (123). This work usually involves applying Extract Method [F]. If the code you're transforming into a Composed Method accumulates information to a common variable, consider applying Move Accumulation to Collecting Parameter (313).

If your method is long because it contains a large switch statement for dispatching and handling requests, you can shrink the method by using Replace Conditional Dispatcher with Command (191).

If you use a switch statement to gather data from numerous classes with different interfaces, you can shrink the size of the method by applying Move Accumulation to Visitor (320).

If a method is long because it contains numerous versions of an algorithm and conditional logic to choose which version to use at runtime, you can shrink the size of the method by applying Replace Conditional Logic with Strategy (129).

Amazon


Refactoring to Patterns (The Addison-Wesley Signature Series)
Refactoring to Patterns
ISBN: 0321213351
EAN: 2147483647
Year: 2003
Pages: 103

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net