Unless checked the length of methods tends to grow without bound. Changes to functionality result in a developer adding additional functionality to an existing method to acheive their current requirement. The method gets longer and more complex, and this has a number of negative consequences.
  • Beyond a point the human mind simply can't deal with complexity efficiently. This leads to fragile, buggy code that can't be altered because the side effects cannot be adequately predicted.
  • As logic is encapsulated in large blocks it becomes more difficult to reuse the existing code. This leads duplicate logic tends to proliferate in the codebase. Duplicate logic causes additional maintainance effort and increases the risk of inconsistent behaviour due to changes not being made consistently in every location.
  • Large methods are more difficult to unit test as the number of paths through each method is significantly higher.
When you find large methods in your codebase, there are a number of refactorings that can assist in managing them. I recommend Martin Fowler's Refactoring: Improving the Design of Existing Code as a solid introduction to this topic. One of the simplest mechanisms for simplifying methods is the Extract Method refactoring, which breaks out parts of a method into another method. A number of tools provide automated support for this refactoring that will reduce the risks involved in modifiying the code, including Visual Studio (as of Visual Studio 2005) and my favourite tool Jetbrains Resharper.

Extract method is relatively straightforward if the logic to be extracted always applies to the same elements. The biggest issues in this case tend to be things like managing the parameter list and the perenial struggle to give the new method a meaningful name. However if you wish to apply the same logic to different elements then things become more complicated. This can result in the extracted method having to carry additional conditional logic that reduces its reusability and makes it more difficult to understand and modify. As this tends to defeat the purpose of extracting the method this is considered less than ideal. In future posts I will be discussing features available in C# 2.0 that can be used to address this problem, then considering how the use of C# 3.0 can improve these solutions.