Tuesday, April 20, 2010

Reusable Logic inside a Non-Reusable Method

I recently encountered a method like this:


void calculateSomething(Map map,String factor,int mode){
       ....
       //calculation steps
       ....
       map.put("caculatedValue",output);
}
This method was a private method and It should have been called from only one place at the time of writing. When I wanted to calculate the same value somewhere else in the program, I need to prepare a map just to satisfy this method.

Still, I wont be sure if I should keep something inside the map so that I wont break the contract. That is, to use this method I need to go through it thoroughly. The contract on the map is not intuitive and clients can break the contract easily.

Things can get worse if the map is passed as an argument to another method.

The solution I came up with is to extract a method[Refactoring, Martin Fowler] and make the method sequentially cohesive [Code Complete,Steve McConnell].

The caller code after refactoring:

int calculatedValue=calculateSomething(String factor,int mode);

map.put("caculatedValue",output);


The reusable method that was not visible initially:
calculateSomething(String factor,int mode){
         ....
         calculation steps
         ....
         return output;
}

Conclusion:
There are methods that might do something reusable + something not required for all callers.
The idea is to make the reusable part clearly visible. Speculation on this idea might lead to extraction of many small methods. It is always better go with evidence.

No comments:

Post a Comment