Tips & Tricks

IntelliJ IDEA Inspection Settings for Refactoring to Java 8

I’ve been giving a talk this year showcasing how to use IntelliJ IDEA inspections to help you refactor existing code to Java 8. The initial version of this, the one I gave at DevoxxUK (video), is based on my Migrating to Java 8 Tutorial. I’ve also written before about how IntelliJ IDEA can help you write more idiomatic Java 8 code.

I’m revisiting the topic now that IntelliJ IDEA 2016.3 has added even more support for
identifying areas of code that can utilise Java 8 idioms and APIs, and making better use of those areas that already use Java 8. I’ve updated the presentation to use these new inspections, and performance tested the results when applied to a specific codebase. Let’s take a look at which inspections are used, how you configure them, and go into detail about what some of them do.

1-inspectionsselected

Here are the inspections that I’ve turned on for the presentation. Not all of them feature in
the specific code that I highlight, but they’re all valuable for locating areas of code that can
be migrated to Java 8.  We’ll look at a few of them in a bit more detail.

Firstly, in IntelliJ IDEA 2016.3 note that the “foreach loop can be collapsed with Stream API” inspection has been updated – see the checkbox in the bottom right? “Suggest to replace with forEach or forEachOrdered”?

Foreach Inspection Updated in IntelliJ IDEA 2016.3

By default this is not ticked. Which means code that originally was highlighted by this inspection when using 2016.2 may not be flagged in 2016.3 if you haven’t selected the checkbox. For example, IntelliJ IDEA will only give a warning about the code below if this checkbox is ticked:

final Set<Class<?>> entities = reflections.getTypesAnnotatedWith(Entity.class);
for (final Class<?> aClass : entities) {
    m.map(aClass);
}

If you apply the change, the code is simplified to use the forEach() method from Iterable, since Set implements Iterable

final Set<Class<?>> entities = reflections.getTypesAnnotatedWith(Entity.class);
entities.forEach(m::map);

My preference is to inline variables where they’re not really adding anything (sometimes variable names are useful to document intermediate steps, but that’s not really necessary in this case), so the code simplifies further if you use Ctrl + Alt + N on the variable:

reflections.getTypesAnnotatedWith(Entity.class).forEach(m::map);

This inspection “foreach loop can be collapsed” identifies numerous places which use a traditional for loop but suggests a number of different alternatives to replace it with, including forEach (with and without the Streams API), and collect. This is covered in more detail in the Migrating to Java 8 Tutorial.

This inspection was around in IntelliJ IDEA 2016.2, but has been updated in 2016.3 – not only with the ability to turn on or off the suggestion to use forEach, but also to provide better alternatives to refactor to, and suggest new places that can use the Streams API.

By better alternatives, I mean that IntelliJ IDEA has become even smarter with how it refactors code. Take a look at this example:

if (listOfIndexes != null) {
    for (final Indexes indexes : listOfIndexes) {
        if (indexes.value().length > 0) {
            for (final Index index : indexes.value()) {
                if (index.fields().length != 0) {
                    ensureIndex(mc, dbColl, index.fields(), index.options(), background, parentMCs, parentMFs);
                } else {
                    ensureIndex(dbColl, index, background);
                }
            }
        }
    }
}

In IntelliJ IDEA 2016.2, this would have been refactored to:

if (listOfIndexes != null) {
    listOfIndexes.stream()
                 .filter(indexes -> indexes.value().length > 0)
                 .forEach(indexes -> {
                     for (final Index index : indexes.value()) {
                         if (index.fields().length != 0) {
                             ensureIndex(mc, dbColl, index.fields(), index.options(), background, 
                                         parentMCs, parentMFs);
                         } else {
                             ensureIndex(dbColl, index, background);
                         }
                     }
                 });
}

But in IntelliJ IDEA 2016.3 both for loops are folded into the stream operation via flatMap

if (listOfIndexes != null) {
    listOfIndexes.stream()
                 .filter(indexes -> indexes.value().length > 0)
                 .flatMap(indexes -> Arrays.stream(indexes.value()))
                 .forEach(index -> {
                     if (index.fields().length != 0) {
                         ensureIndex(mc, dbColl, index.fields(), index.options(), background, 
                                     parentMCs, parentMFs);
                     } else {
                         ensureIndex(dbColl, index, background);
                     }
                 });
}

In this specific case the code is still not a perfect example of using streams, as we have a if/else which cannot be folded into the stream, and an initial null check. Also remember that although using forEach is a good first step towards understanding and using streams, it’s often a sign that the operation could perhaps be redesigned to use a more efficient stream operation that doesn’t need to process every item.

Another example of the improvements is how IntelliJ IDEA has become smarter about identifying code that sorts Collections, and suggesting alternatives. For example, this is typical pre-Java-8 code:

final List<LogLine> lineToLog = new ArrayList<LogLine>();
for (final ConstraintViolation violation : violations) {
    lineToLog.add(new LogLine(violation));
}
sort(lineToLog);

Previously, IntelliJ IDEA suggested this could be simplified to:

final List<LogLine> lineToLog = violations.stream()
                                          .map(LogLine::new)
                                          .collect(Collectors.toList());
sort(lineToLog);

It took a vigilant developer to notice that the sort method can actually be folded into the stream operation. Now, IntelliJ IDEA does this for you:

final List<LogLine> lineToLog = violations.stream()
                                          .map(LogLine::new)
                                          .sorted()
                                          .collect(Collectors.toList());

 

As well as improved suggestions for refactoring, IntelliJ IDEA 2016.3 also identifies more areas that can use Stream operations. In particular, it can suggest that areas that iterate over arrays or use indexed loops can be refactored. For example, consider this code that loops over an array:

public static List<Field> getValidFields(Field[] fields, boolean returnFinalFields) {
    final List<Field> validFields = new ArrayList<Field>();
    // we ignore static and final fields
    for (final Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers()) 
                && (returnFinalFields || !Modifier.isFinal(field.getModifiers()))) {
            validFields.add(field);
        }
    }
    return validFields;
}

The inspection suggests that this can be refactored to:

public static List<Field> getValidFields(Field[] fields, boolean returnFinalFields) {
    final List<Field> validFields = Arrays.stream(fields)
                                          .filter(field -> !Modifier.isStatic(field.getModifiers()) &&
                                                           (returnFinalFields || 
                                                            !Modifier.isFinal(field.getModifiers())))
                                          .collect(Collectors.toList());
    // we ignore static and final fields
    return validFields;
}

We can refactor more to improve the readability further. Firstly by inlining the validFields  variable, and then by extracting a method for the complex filter logic. This final step has the nice side effect of letting us remove the comment, since the method name combined with the filter is descriptive enough to show what the code is trying to do

public static List<Field> getValidFields(Field[] fields, boolean returnFinalFields) {
    return Arrays.stream(fields)
                 .filter(field -> isNotStaticOrFinal(field, returnFinalFields))
                 .collect(Collectors.toList());
}

private static boolean isNotStaticOrFinal(Field field, boolean returnFinalFields) {
    return !Modifier.isStatic(field.getModifiers()) 
               && (returnFinalFields || !Modifier.isFinal(field.getModifiers()));
}

But you do need to take care with refactoring code like this. The updated code is easier to read, as it expresses the intention nicely, but iterating over arrays with a traditional for loop is an operation that is efficient for computers. Using Arrays.stream() to turn the array into a Stream will probably have some performance impact. In the grand scheme of things this is likely to be negligible, but if performance matters in your application you should test this impact.

One of the new inspections available in 2016.3 is the ability to locate places where Collections.removeIf  can be used. If, for example, you have a Set  of values and you want to remove some items that meet some criteria, you may have code that looks like this:

final Iterator<URL> iterator = urls.iterator();
while (iterator.hasNext()) {
    final URL url = iterator.next();
    if (url.getPath().endsWith("jnilib")) {
        iterator.remove();
    }
}

The “Loop can be replaced with Collection.removeIf” inspection suggests this can be refactored to:

urls.removeIf(url -> url.getPath().endsWith("jnilib"));

This code is clearly much simpler, the boilerplate for managing the iteration has disappeared and we’re left with only the condition to check each item against.

Another new inspection is around Comparators. Of course, Comparators can now be implemented as lambda expressions rather than the traditional anonymous inner class, but what is less obvious is that there are new helpers on the Comparator class than can simplify many of these even further. Consider the following code:

final Set<Constraint> ve = new TreeSet<>((constraint1, constraint2) -> constraint1.getLevel().compareTo(constraint2.getLevel()));

The “Use Comparator combinators” inspection suggests we change this to

final Set<Constraint> ve = new TreeSet<>(Comparator.comparing(Constraint::getLevel));

It’s less code, but more usefully the important information now stands out more – the Constraint values in the TreeSet will be ordered by their Level.

There are more new inspections, and more examples of improvements to the existing inspection suggestions. To see some of those mentioned here in action, and some more new ones, check out the Java 8 Inspections Screencast.

And to see these inspections being used against a real code base, with details of the performance implications of these changes, take a look at my Refactoring to Java 8 presentation from Devoxx Belgium last month

Whether you’re only just considering enabling the Java 8 inspections, or have previously checked them out but not felt compelled to use them, do take a look at them in IntelliJ IDEA 2016.3, you may be surprised at how much they can simplify your code.

image description