Saturday, October 28, 2006

Refactoring: Replace Method with Method Object

Well, reading Refactoring book from Martin Fowler, I feel some case of the refactoring I have used before without realizing it. The most interesting I have found so far is Replace Method with Method Object. The idea is if your method is too long, you should find a way to shorten it to make it more readable and self-explained. Well, self-explained can be done using comment in the code. But sometimes comment can be over killed too. Some expert suggest that too much comment means your code is not refactored well-enough. So, in the book, it suggest you to use Extract Method.

I hope below sample can explain what Extract Method, although it's too simple:
void LongFunction(...)
{
// very long function here
foreach(int item in items)
if (item % 2 == 0)
isEven = true;
// another very long function
}

Applying Extract Method, it will be:

void LongFunction(...)
{
// very long function here

foreach(int item in items)
isEven = IsNumberEven(item)
// another very long function
}


bool IsNumberEvem(int item)
{
if (item % 2 == 0)
return true;
else
return false;
}

Ok, most of the cases Extract Method can be used, as Fowler said, 99% cases. But some extreme cases, that you use too much local variable will be very difficult to apply Extract Method, another ways to do are Introduce Parameter Object, Preserve Whole Object, and Replace Method with Method Object.

Well, what I have experienced before is I have a function that is to do Invoice Calculation. This Invoice Calculation include bunch of variable, local object, etc, and quite long of code and logic. This calculation is used in so many places, like Creating Invoice, Check GIRO, Apply GIRO, etc. So, with Replace Method with Method Object, I create totally new class to do Invoice Calculation. All temporary variable and local object are created as class fields/properties. After applying all the logic into the new method inside the new class, I start to refactor using Extract Method. After series of retesting, I found the new code is far easier to read and maintain. The InvoiceCalculation object can be reused easily, without using too many local variable/paremeter. And, another aspect, I can focus on tweaking the performance easier.

The interesting point, I did this before reading the refactoring technique. After reading, I can apply more understandable word to explain what I am doing. Good book, try yourself.