Long Method

25 08 2011

The longer a procedure is, the more difficult it is to understand. Lots of long methods often lead to code duplication. By breaking these down into smaller methods you can find ways for logic to be shared. Older languages carried an overhead in subroutine calls, which deterred people from small methods. Modern OO languages have pretty much eliminated that overhead for in-process calls. The real key to making it easy to understand small methods is good naming. If you have a good name for a method you don’t need to look at the body.

You should be much more aggressive about decomposing methods. A guide to follow is that whenever you feel the need to comment something, write a method
instead. Such a method contains the code that was commented but is named after the intention of the code rather than how it does it. You can do this on a group of lines or on as little as a single line of code.

Advertisements




Duplicated Code

9 08 2011

Duplicated code is the smelliest of code smells and the most pervasive. It can be present in explicit or subtle form. Explicit duplication is present where identical code (copy and paste style) is found. Subtle duplication is found where structures or processing steps exist that appear different but are essentially the same.

The simplest duplicated code problem is when you have the same expression in two methods of the same class. Then all you have to do is Extract Method and invoke the code from both places. More complex examples exist such as duplicate processing logic simply because types have different interfaces, duplicate code in constructors, algorithms that are the same except for an object creation step. In these cases refactorings like Chain Constructors, Introduce Polymorphic Creation with Factory Method and Unify Interfaces with Adapter can help you stay DRY (don’t repeat yourself).