Generate, rename and delete getters/setters instantly in Eclipse

Despite the arguments and debates about getters and setters in Java, the fact is that they’re a reality and you have to work with them.

But managing getters and setters is a time-consuming effort. Creating a getter/setter for 5 fields in a class can take minutes, renaming one is error-prone and deleting one is just plain inconvenient.

There are options like Project Lombok (that implicitly creates getters/setters without the need to code them) and you could avoid getters/setters altogether by redesigning your classes.

But these options aren’t always available, so it’s a good thing Eclipse has some handy features for managing getters and setters. Combined with the ability to generate constructors based on fields, you can get the boilerplate code out of the way in seconds and get on with the real coding.

(more…)

Convert nested/anonymous classes into top level classes using Eclipse refactoring

Nested classes, eg. anonymous classes, are often more convenient than creating separate classes, especially when working with something like the Command pattern or event listeners. For example:

JButton button = new JButton();
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // ... Do something useful
    }
});

But there comes a point when the nested class becomes so bulky that code becomes unreadable. And sometimes you want to reuse the same class in another place – something that’s difficult with anonymous inner classes.

The answer would be to change the nested class into a top level public class (or a first-class citizen, if you like) that exists in its own file (eg. SomethingUsefulActionListener.java). But doing this manually can take a lot of time and is error-prone.

Eclipse has a couple of refactorings and quick fixes that help to make the job a lot easier. Converting an anonymous inner class to a top level class requires two refactorings only and will take you a couple of seconds instead of minutes. A (named) inner class takes only one refactoring. And passing arguments to the new class is also easy if you use some of Eclipse’s Quick Fixes.

(more…)

Add comments and Javadocs in Eclipse with a single keystroke

When you want to work with comments in Eclipse, you could use the slow way of moving to the start of the line, pressing // and then repeating this for all the lines you have.

Or you could use the quick way of adding a comment with a single keystroke no matter where the cursor’s positioned in the statement.

The same goes for Javadocs – there are just too many things to type before you can start commenting the good stuff. That’s why Eclipse also has a shortcut that let’s you add Javadoc to a field, method or class.

(more…)

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 = "shovel and spade";
...
String otherTools = "shovel and spade";

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.

(more…)

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.

(more…)

Automatically place a semicolon at the end of Java statements in Eclipse

We all know that Java statements are terminated by a semicolon (;), but they’re a bit of a pain to add to the end of a line. One way would be to press End (to move to the end of the line) then press semicolon, but this is tedious. Because this is something that you do often it’s worth learning how to do this faster.

It’s a good thing Eclipse can automatically put the semicolon at the end of the line, no matter where you are in the statement. It’s as easy as setting one preference and there’s a bonus preference for adding braces to the correct position as well. For something so small, it saves a lot of time.

So in the example below, if you imagine that your cursor is placed after the word blue since you were editing the string. Pressing semicolon will cause Eclipse to place the semicolon after the closing bracket at the end. Nice.


System.out.println("The house is blue")

(more…)

Add, remove and reorder a method’s arguments instantly across multiple classes in Eclipse

When refactoring, one thing that sometimes changes is a method’s signature (ie. its return type, number of arguments, argument types and order).

For some it may not happen that often, but the job becomes difficult when you have a dozen or more classes that call that method. All of them need to be changed to match the new signature and this can take a long time to change.

Fortunately, Eclipse has a refactoring called Change Method Signature that makes this easy, allowing a signature change in almost no time across any number of classes. This can be a huge timesaver when you need it and save you hours of frustration trying to fix red crosses in Eclipse.

(more…)

Generate static imports in Eclipse on autocomplete for JUnit Assert, StringUtils and others

Eclipse normally adds import statements for you when you autocomplete a type, press Ctrl+Shift+O or organise imports when you save. However, by default it doesn’t do the same for static imports, something you’ll miss when using classes like JUnit’s Assert and Apache Commons’ StringUtils. This means having to add import statements manually, which takes unnecessary time.

So, in the code below, I want to be able to autocomplete assertEquals (line 7) and have Eclipse add a static import for org.junit.Assert.assertEquals (line 1).

import static org.junit.Assert.assertEquals;
...
public class MyTest {
   @Test
   public void testSomething() throws Exception {
      assertEquals(1, 1);
   }

Now, the good news is that there is a way to automatically add static imports when you use autocomplete. It’s done via a preference that tells Eclipse which static classes you want to include for Content Assist (autocomplete). I show you how to do this below.

The bad news is that there doesn’t seem to be a way to tell the Organise Imports command to add static imports. However, a working autocomplete should already cater for 90% of your coding needs, so the bad news isn’t that bad.

(more…)

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("The year " + year + " is a leap year.");

Into this:

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

(more…)

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.

(more…)

Follow

Get every new post delivered to your Inbox.