Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

An Introduction to Refactoring with IntelliJ IDEA

$
0
0

1. Overview

Keeping the code tidy is not always easy. Fortunately for us, our IDEs are pretty smart nowadays and can help us in achieving this. In this tutorial, we’re going to focus on IntelliJ IDEA, the JetBrains Java code editor.

We’ll see a few features offered by the editor to refactor code, from renaming variables to changing a method signature.

2. Renaming

2.1. Basic Renaming

First, let’s start with the basics: renaming. IntelliJ offers us the possibility to rename different elements of our code: types, variables, methods, and even packages.

To rename an element, we need to follow these steps:

  • Right-click the element
  • Trigger the Refactor > Rename option
  • Type the new element name
  • Press Enter

By the way, we can replace the first two steps by selecting the element and pressing Shift + F6.

When triggered, the renaming action will search across the code for every usage of the element and then change them with the provided value.

Let’s imagine a SimpleClass class with a poorly named addition method, someAdditionMethod, called in the main method:

public class SimpleClass {
    public static void main(String[] args) {
        new SimpleClass().someAdditionMethod(1, 2);
    }

    public int someAdditionMethod(int a, int b) {
        return a + b;
    }
}

Thus, if we choose to rename this method into add, IntelliJ will produce the following code:

public class SimpleClass() {
    public static void main(String[] args) {
        new SimpleClass().add(1, 2);
    }

    public int add(int a, int b) {
        return a + b;
    }
}

2.2. Advanced Renaming

However, IntelliJ does more than searching for code usages of our elements and rename them. As a matter of fact, a few more options are available. IntelliJ can also search for occurrences in comments and strings, and even in files that don’t contain source code. As for parameters, it can rename them in the class hierarchy in case of overridden methods.

Those options are available by hitting Shift + F6 once more before renaming our element and a popup will appear:

The Search in comments and strings option is available for any renaming. As for the Search for text occurrences option, it’s not available for method parameters and local variables. Finally, the Rename parameters in hierarchy option is available for method parameters only.

So, if any match is found with one of those two options, IntelliJ will show them and offer us the possibility to opt out of some of the changes (say, in case it matches something unrelated with our renaming).

Let’s add some Javadoc to our method, and then rename its first parameter, a:

/**
  * Adds a and b
  * @param a the first number
  * @param b the second number
  */
public int add(int a, int b) {...}

By checking the first option in the confirmation pop-up, IntelliJ matches any mention of the parameters in the Javadoc comment of the method and offers to rename them as well:

/**
  * Adds firstNumber and b
  * @param firstNumber the first number
  * @param b the second number
  */
public int add(int firstNumber, int b) {...}

Finally, we must note that IntelliJ is smart and searches mostly for usages in the scope of the renamed element. In our case, that would mean that a comment situated outside the method (except for the Javadoc) and containing a mention to a would not have been considered for renaming.

3. Extracting

Now, let’s talk about extraction. Extraction enables us to grab a piece of code and put it into a variable, a method or even a class. IntelliJ handles this pretty smartly as it searches for similar pieces of code and offers to extract them in the same way.

So, in this section, we’ll learn how to leverage the extraction feature offered by IntelliJ.

3.1. Variables

First, let’s start with variables extraction. That means local variables, parameters, fields, and constants. To extract a variable, we must follow these steps:

  • Select an expression that fits in a variable
  • Right-click the selected area
  • Trigger the Refactor > Extract > Variable/Parameter/Field/Constant option
  • Choose between the Replace this occurrence only or Replace all x occurrences options, if proposed
  • Enter a name for the extracted expression (if the chosen one doesn’t suit us)
  • Press Enter

As for renaming, it’s possible to use keyboard shortcuts instead of using the menu. The default shortcuts are, respectively, Ctrl + Alt + V, Ctrl + Alt + P, Ctrl + Alt + F and Ctrl + Alt + C.

IntelliJ will try to guess a name for our extracted expression, based on what the expression returns. If it doesn’t match our needs, we’re free to change it before confirming the extraction.

Let’s illustrate with an example. We could imagine adding a method to our SimpleClass class telling us if the current date is between two given dates:

public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
    return LocalDate.now().isAfter(startingDate) && LocalDate.now().isBefore(endingDate);
}

Let’s say we want to change our implementation because we use LocalDate.now() twice and we would like to make sure it has the exact same value in both evaluations. Let’s just select the expression and extract it in a local variable, now:

Then, our LocalDate.now() call is captured in a local variable:

public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
    LocalDate now = LocalDate.now();
    return now.isAfter(startingDate) && now.isBefore(endingDate);
}

By checking the Replace all option, we made sure that both expressions have been replaced at once.

3.2. Methods

Let’s now check how to extract methods using IntelliJ:

  • Select the expression or lines of code fitting the method we want to create
  • Right-click the selected area
  • Trigger the Refactor > Extract > Method option
  • Type in the method information: its name, its visibility and its parameters
  • Press Enter

Hitting Ctrl + Alt + M after selecting the method body works as well.

Let’s reuse our previous example and say we want to have a method checking if any date is between to other dates. Then, we would just have to select our last line in the isNowBetween method and trigger the method extraction feature.

In the opened window, we can see that IntelliJ has already spotted the three needed parameters: startingDate, endingDate and now. As we want this method to be as generic as possible, we rename the now parameter into date. And for cohesion purposes, we place it as the first parameter.

Finally, we give our method a name, isDateBetween, and finalize the extraction process:

We would then obtain the following code:

public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
    LocalDate now = LocalDate.now();
    return isDateBetween(now, startingDate, endingDate);
}

private static boolean isDateBetween(LocalDate date, LocalDate startingDate, LocalDate endingDate) {
    return date.isBefore(endingDate) && date.isAfter(startingDate);
}

As we can see, the action triggered the creation of the new isDateBetween method, which is also called in the isNowBetween method. The method is private, by default. Of course, this could have been changed using the visibility option.

3.3. Classes

After all that, we might want to get our date-related methods in a specific class, focused on dates management, let’s say: DateUtils. Again, this is pretty easy:

  • Right-click in the class that has our elements we want to move
  • Trigger the Refactor > Extract > Delegate option
  • Type in the class information: its name, its package, the elements to delegate, the visibility of those elements
  • Press Enter

By default, no keyboard shortcut is available for this feature.

Let’s say, before triggering the feature, that we call our date-related methods in the main method:

isNowBetween(LocalDate.MIN, LocalDate.MAX);
isDateBetween(LocalDate.of(2019, 1, 1), LocalDate.MIN, LocalDate.MAX);

Then we delegate those two methods to a DateUtils class using the delegate option:

Trigger the feature would produce the following code:

public class DateUtils {
    public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
        LocalDate now = LocalDate.now();
        return isDateBetween(now, startingDate, endingDate);
    }

    public static boolean isDateBetween(LocalDate date, LocalDate startingDate, LocalDate endingDate) {
        return date.isBefore(endingDate) && date.isAfter(startingDate);
    }
}

We can see that the isDateBetween method has been made public. That is the result of the visibility option, that is set to escalate by default. Escalate means that visibility will be changed in order to ensure current calls to the delegated elements are still compiling.

In our case, isDateBetween is used in the main method of SimpleClass:

DateUtils.isNowBetween(LocalDate.MIN, LocalDate.MAX);
DateUtils.isDateBetween(LocalDate.of(2019, 1, 1), LocalDate.MIN, LocalDate.MAX);

Thus, when moving the method it’s necessary to make it not private.

However, it’s possible to give specific visibility to our elements by selecting the other options.

4. Inlining

Now that we covered extraction, let’s talk about its counterpart: inlining. Inlining is all about taking a code element and replace it with what it’s made of. For a variable, this would be the expression it has been assigned. For a method, it would be its body.

In order to inline an element, we must right-click this element – either its definition or a reference to it – and trigger the Refactor > Inline option. We can also achieve this by selecting the element and hitting the Ctrl + Alt + N keys.

At this point, IntelliJ will offer us multiple options, whether we wish to inline a variable or a method, whether we selected a definition or a reference. These options are:

  • Inline all the references and remove the element
  • Inline all the references, but keep the element
  • Only inline the selected reference and keep the element

Let’s take our isNowBetween method and get rid of the now variable, which now seems a bit overkill:

By inlining this variable, we would obtain the following result:

public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
    return isDateBetween(LocalDate.now(), startingDate, endingDate);
}

In our case, the only option was to remove all the references and remove the element. But let’s imagine we also want to get rid of the isDateBetween call and choose to inline it. Then, IntelliJ would offer us the three possibilities we spoke about before:

Choosing the first one would replace all calls with the method body and delete the method. As for the second one, it would replace all calls with the method body but keep the method. And finally, the last one would only replace the current call with the method body:

public class DateUtils {
    public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
        LocalDate date = LocalDate.now();
        return date.isBefore(endingDate) && date.isAfter(startingDate);
    }

    public static boolean isDateBetween(LocalDate date, LocalDate startingDate, LocalDate endingDate) {
        return date.isBefore(endingDate) && date.isAfter(startingDate);
    }
}

Our main method in the SimpleClass remains untouched as well.

5. Moving

Earlier, we saw how to create a new class and delegate some of our code elements to it. But there are times we might want to delegate a method to an existing class. That’s what this section is about.

In order to move an element, we must follow these steps:

  • Select the element to move
  • Right-click the element
  • Trigger the Refactor > Move option
  • Choose the recipient class and the method visibility
  • Press Enter

We can also achieve this by pressing F6 after selecting the element.

Let’s say we add a new method to our SimpleClass, isDateOutstide(), that will tell us if a date is situated outside an interval of dates:

public static boolean isDateOutside(LocalDate date, LocalDate startingDate, LocalDate endingDate) {
    return !DateUtils.isDateBetween(date, startingDate, endingDate);
}

We then realize that its place should be in our DateUtils class. So we decide to move it:

Our method is now in the DateUtils class. We can see that the reference to DateUtils inside the method has disappeared as it’s no longer needed:

public static boolean isDateOutside(LocalDate date, LocalDate startingDate, LocalDate endingDate) {
    return !isDateBetween(date, startingDate, endingDate);
}

The example we just did works well as it concerns a static method. However, in the case of an instance method, things are not so straight-forward.

If we want to move an instance method, IntelliJ will search for classes referenced in the fields of the current class and offer to move the method to one of those classes (provided they are ours to modify).

If no modifiable class is referenced in the fields, then IntelliJ proposes making the method static before moving it.

6. Changing a Method Signature

Finally, we’ll talk about a feature allowing us to change a method signature. The purpose of this feature is to manipulate every aspect of a method signature.

As usual, we must go through a few steps to trigger the feature:

  • Select the method to change
  • Right-click the method
  • Trigger the Refactor > Change signature option
  • Bring changes to the method signature
  • Press Enter

If we prefer to use keyboards shortcut, it’s possible to use Ctrl + F6 as well.

This feature will open a window very similar to the method extraction feature. And so we have the same possibilities that when we extract a method: changing its name, its visibility and also adding/removing parameters and fine-tuning them.

Let’s imagine we want to change our implementation of isDateBetween to either consider the date bounds as inclusive or exclusive. In order to do that we want to add a boolean parameter to our method:

By changing the method signature we can add this parameter, name it and give it a default value:

public static boolean isDateBetween(LocalDate date, LocalDate startingDate,
   LocalDate endingDate, boolean inclusive) {
    return date.isBefore(endingDate) && date.isAfter(startingDate);
}

After that, we just have to adapt the method body according to our needs.

If we wanted, we could have checked the Delegate via overloading method option in order to create another method with the parameter instead of modifying the current one.

7. Conclusion

In this article, we had the chance to deep dive into some of the refactoring features offered by IntelliJ. Of course, we didn’t cover all the possibilities as IntelliJ is a very powerful tool. To learn more about this editor, we can always refer to its documentation.

We saw a few things like how to rename our code elements and how to extract some behaviors into variables, methods or classes. We also learned how to inline some elements if we didn’t need them standing alone, move some code elsewhere or even fully change an existing method signature.


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>