Essential tools to manage import statements in Eclipse

It’s a big hassle to manually organise package import statements so it’s important to know what tools are available so your IDE can handle imports as quickly and quietly as possible.

Adding import statements for missing references and removing unused imports can take ages and the list of imports can get very long and hard to manage. As an example, the import statements below can consist of static/normal imports and wildcard/class imports:

// The list of imports can get really long...
import static org.junit.Assert.assertEquals; // Static imports
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.lang.*; // Wildcard; unused so should be removed
...
public class MyTest {
   @Test
   public void testSomething() throws Exception {
      List<String> messages = new ArrayList<String>();
      assertEquals(1, 1);
   }
}

To make life easier, Eclipse has a heap of features that automatically manage import statements, including organising them when you save or when you press a keyboard shortcut. It can even deal with static imports. This tip covers some of these features, starting with the absolute essentials that save loads of time and moving on to more optional features that will depend on your environment and tastes.

Continue reading

Extract constants from strings and numbers with Eclipse refactorings

For readability’s sake, it’s almost always a good idea to replace magic numbers and string literals with constants. That’s all good, but it can take a bit of time to refactor these to constants, especially strings or parts of strings.

For example, in the code below we want to refactor “shovel and spade” to a private static final String called TOOLS. To do that manually would take some time. It goes even slower if we only want to extract “spade” to a constant because we first have to convert the string to a concatenation.

String tools = &quot;shovel and spade&quot;;
...
String otherTools = &quot;shovel and spade&quot;;

Luckily, Eclipse has a couple of ways to instantly convert literals to constants. Coupled with tools to speed up string selection and to pick out part of a string, you have the ability to create a constant in about 2 seconds flat. I’ll discuss all these features below.

Continue reading

Navigate and fix errors and warnings in a class with Eclipse keyboard shortcuts

I really don’t like it when Eclipse shows errors/warnings annotations in a class. It’s sometimes nice to jump from one to the next and clean out a class one line at a time, but most of the time they’re just distractions, so I want to be able to find and fix them fast.

So there must be a better way to jump between the errors/warnings¬† than to use the mouse or page down to the next error. These methods are not only slow but often frustrating because you tend to miss the annotation, especially if it’s a big class. And navigating to the Problems view using the keyboard is ok, but sometimes overkill for just clearing out errors/warnings in one class.

A good thing then that Eclipse offers keyboard shortcuts that take you to the next/previous annotation in the class. And it does so in a way that selects the annotation immediately, allowing you to use Quick Fix (Ctrl+1) to fix it fast. So here’s how to use these shortcuts to navigate between the error/warning annotations and fix some of the errors easily.

Continue reading

Generate class constructors in Eclipse based on fields or superclass constructors

You’ll often need to add a constructor to a class based on some/all of its fields or even based on constructors of its superclass. Take the following code:

public class Contact {
    private String name, surname;
    private int age;

    public Contact(String name, String surname, int age) {
        this.name = name;
        this.surname = surname;
        this.age = age;
    }
}

That’s 5 lines of code (lines 5-9) just to have a constructor. You could write them all by hand, but writing a constructor that accepts and initialises each field takes a lot of time and becomes irritating after a while. And creating constructors from a superclass can take even longer because the superclass can define multiple constructors that you need to reimplement.

That is why Eclipse has two features to help you generate these constructor instantly: Generate Constructor using Field and Generate Constructor from Superclass. Both features will generate a constructor in seconds, freeing you up to get to the exciting code. You’ll also see how to add/remove/reorder arguments of an existing constructor based on fields defined in the class.

Continue reading

Convert string concatenations into StringBuilder or MessageFormat calls with Eclipse’s Quick Fix

Eclipse sports a really nice Quick Fix that turns string concatenations into the recommended calls to StringBuilder. It saves you the time of creating a variable, having to pull out each of the string parts into a call to StringBuilder’s append and then using the string with toString().

So with one key, it will turn code like this:

System.out.println(&quot;The year &quot; + year + &quot; is a leap year.&quot;);

Into this:

StringBuilder message = new StringBuilder();
message.append(&quot;The year &quot;);
message.append(year);
message.append(&quot; is a leap year.&quot;);
System.out.println(message.toString());

Continue reading

Join/split if statements and rearrange expressions using Eclipse Quick Fix

A common cause of bad readability is nested if statements, especially when they could be combined into one if with an AND (&&). This also opens the opportunity to extract private methods to make the if more readable. While you’re at it, you might also want to rearrange the expressions so they make more logical sense.

But making these changes can be tedious and time consuming and often error-prone. It may not happen that frequently, but when it does you want it to go as fast as possible.

Eclipse comes to the rescue with a quick fix that allows you to join or split the statements in one keystroke. And the quick fix allows you to rearrange expressions on the if statement as well.

Continue reading