Long list of parameters in a method, though common in procedural code are difficult to understand and likely to be volatile.
Example
public void paintComponent( Graphics gr, Component renderer, Container parent, int x, int y, int width, int height, Boolean shouldValidate)
Cause:
You might be trying to minimize coupling between objects. Instead of the called object being aware of relationship between classes, you let the caller locate everything; then the method concentrates on what is being asked to do with the pieces.
Or a programmer generalizes the routine to deal with multiple variations by creating a general algorithm and a lot of control parameters
Refactoring:
There have couple of refactoring ways to reduce long parameter
- Replace Parameter with method
- Introduce Parameter Object
- Preserve Whole Object
1. Replace Parameter with method
use replace parameter with method when you can get the data in one parameter by making a request of an object you already know about. This object might be a field or it might be another parameter.
Mechanics
- If necessary, extract the calculation of the parameter into a method
- Replace references to the parameter in method bodies with references to the method
- Compile and test after each replacement
- Use Remove Parameter on the parameters
Following code is an example where we can replace the parameter using method. The discount level can be called inside discountPrice method. It does not need to pass as parameter.
Now I will refactor the above code using Resharper. To begin we can extract a method for calculation of discount level.
In visual studio select the line you want to extract as method using Resharper. After that you can right click as image or can use Control+R, M
Give proper name of the method
After extracting method, code looks like
Now Inline the method inside as parameter using Resharper
The code state
Again do inline for discountPrice parameter
The next window you can select discountLevel
The code will change will be as
You can also move the Temporary variable basePrice using Extract Method and Inline refactoring technique.
The final state of code looks like
Resharper is very good tool you can use for refactoring without the fear of breaking code. But it is recommended to compile your code after each refactoring.
This code look much better and organized after removing unnecessary parameters.
In the next article I will continue other refactoring techniques to reduce Long parameter list.
This code is very helpful for us
ReplyDeleteBulk SMS Provider in India
Nice explanation - and a good example on how to work with resharper (Yes It can be done by hand, but that tool is so cool)
ReplyDelete