Quick Tip: IntelliJ – easily updating method calls when method signature changes

The What

I wrote a Java method, whose signature contains a number of parameters. This method is called by many other methods (i use the method in my tests). After a while i realize one of the parameters is not needed anymore. I want to change the method signature and to update all its’ references throughout my code.

The How

Using IntelliJ this change is done by using the Refactoring feature it provides, that helps automatically update all the references to the method, by removing the parameter from all calling methods.

Let’s say you wrote the following method (that has 3 parameters):

public void methodWithParameters(String par1, String par2, String par3) {
    par1 = par1 + ",";
    par2 = par2 + ".";
    System.out.println(par1);
    System.out.println(par2);
    System.out.println(par3);
}

This method is called by two tests:

@Test
public void aSimpleTest() {
    helperMethods.methodWithParameters("one", "two", "three");
}

@Test
public void anotherTest() {
    helperMethods.methodWithParameters("a", "b", "c");
}

You realize parameter par3 is really useless for your purpose, so you want to remove it.

From IntelliJ, click on the method’s signature, then click Refactor and select Change Signature… (or memorize its’ keyboard shortcut for further use, namely Ctrl + F6). The following screen appears, where all the parameters that comprise the methods’ signature are displayed:

paramList

In order to remove a parameter from the signature, click on it, then click the ‘‘ icon on the right hand side. Parameter selection

On the lower side of the Change Signature screen, the preview of the new signature is displayed:

preview

Click the ‘Refactor‘ button on the lower part of the screen. At this time, all methods that call the modified one will only be passing two parameters on the method call:

updatedMethods

The only thing remaining is to update the method whose parameter was removed, by cleaning up the code that used it. After that, job is done – tests will not pass the parameter anymore, and the method that was using it has been cleaned up.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s