Monday, February 22, 2010

Fowler Refactorings - Replace Temp With Query

I started reading Martin Fowler's Refactoring book and am really amazed by the effect of refactorings that he described. Here is one sample example where he talks about replacing local variables.

His take on using local variables -

The problem with temps is that they are temporary and local. Because they can be seen only in the context of the method in which they are used, temps tend to encourage longer methods, because that's the only way you can reach the temp. By replacing the temp with a query method, any method in the class can get at the information. That helps a lot in coming up with cleaner code for the class.


I will show a before and after code layout here.

Class Before refactoring. It contains just one method which calculates price based on baseprice and discount.


public class ReplaceTempWithQuery {
private int quantity;
private int itemPrice;

double getPrice() {
int basePrice = quantity * itemPrice;
double discountFactor;
if (basePrice > 1000) discountFactor = 0.95;
else discountFactor = 0.98;
return basePrice * discountFactor;
}

}

After the code is refactored the resulting class looks like this.


public class ReplaceTempWithQuery {
private int quantity;
private int itemPrice;

double getPrice() {
return basePrice() * discountFactor();
}

private double discountFactor() {
if (basePrice() > 1000)
return 0.95;
else
return 0.98;
}

private int basePrice() {
return quantity * itemPrice;
}

As you can see, the refactored code looks much more readable and also i think its easily testable. Eventhough the example is very simple i think its enough to explain the purpose.

There are several these kind of refactoring discussed in Martin Fowler's book and i think every programmer should read the book atleast once.
I will continue to post these as long as i am not bored :)