Friday, September 11, 2015

Code Smells : Long Parameter List refactoring by Replacing Parameter with Method using Resharper

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.

Capture1[1]


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

Capture2[1]


Give proper name of the method

Capture4[1]


After extracting method, code looks like

Capture5[1]


Now Inline the method inside as parameter using Resharper

Capture6[1]


The code state

Capture7[1]


Again do inline for discountPrice parameter

Capture8[1]


The next window you can select discountLevel

Capture9[1]


The code will change will be as

Capture10[1]


You can also  move the Temporary variable basePrice using Extract Method and  Inline refactoring technique.

The final state of code looks like



Capture11[2]

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.