Disable Eclipse formatting for certain sections of code only

In a previous tip, I showed how to automatically format code every time you save in Eclipse or how to manually format by pressing Ctrl+Shift+F. These work great most of the times but sometimes you want to exclude a certain block of code from formatting, often because the formatting turns out unreadable (ie. ugly) for that particular piece of code.

Eclipse allows you to disable formatting for a certain block or section of code by surrounding that code with formatter comments, known as Off/On tags. And you can also make generating those comments around a block of code extremely simple by creating a simple template.

Continue reading

Quickly declare and initialise lists, maps and arrays with Eclipse templates

Java has a lot of boilerplate code, although each new version tries to remove a bit more every time. One area particularly affected is when you have to declare and initialise lists, maps or sets (some of it hopefully simplified in Java 7). Here’s some sample code:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
...
Map<String, String> map = new HashMap<String, String>();
List<String> list = new ArrayList<String>();
Set<String> set = new HashSet<String>();
String[] array = new String[] {};

To create any of these, you have to type a lot. Sometimes you make a mistake and have to retype. And half a minute later you’ve got one line of code that just declares a list. Also, you can have Eclipse automatically add imports when you save, but Eclipse normally can’t guess the correct List, instead prompting you to choose between java.util.List and java.awt.List (why isn’t there an option to use the former as the default?).

But Eclipse templates can help you avoid the hassle. Not only will it create the correct import statements, but also remove the effort of typing out the same type in the interface and implementation collection. If you’re new to templates, then see this tip to get an overview.

Continue reading

JUnit testing made easier with Eclipse templates

When you’re writing JUnit tests, you’ll often find yourself repeating the same boilerplate code. Take the following code:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class EngineTest {
    @Before
    public void setup() {
        ...
    }

    @Test
    public void test() throws Exception {
        ...
    }

    @After
    public void tearDown() {
        ...
    }
}

If you want to add a test, you have to somehow add lines 3, 11, 12 and 14 before you even get to the actual test. The same holds for setup and teardown code. We know that Eclipse can help with adding imports automatically when you save or autocomplete, but it still takes time to get everything in place.

Eclipse templates can help take away the drudgery by adding all this boilerplate code automatically. It can automatically add a test, setup and teardown methods together with calls to assertEquals, assertTrue and others. I’m assuming JUnit 4 in all the templates. If you’re new to templates, then see this tip to get an overview.

Continue reading

log4j logging made easier with Eclipse templates

Logging statements have taken up a nice chunk of my programming life. Info, debug and warning statements are common, especially since some team standards require that logging be done consistently (eg. at the start and end of all methods). Take the following code:

import org.apache.log4j.Logger;
...
public class Engine {
    private final static Logger logger = Logger.getLogger(Engine.class);

    public void someMethod() {
        ...
        logger.debug("Doing something here");
        ...
    }

To get the statement on line 8 you first have to insert line 4, generate the import on line 1 (eg. with Ctrl+Shift+O) and then move back to line 8 to type out the statement. That’s a lot of time for just one statement.

So here are some templates to help with this. The templates assume log4j since most people use that (right?), but can easily be adapted for Java Logging or other framework. If you’re new to templates, then see this tip to get an overview.

Continue reading

Generate validation code for required variables using templates

You may find yourself having to write the following code once too often, especially at the start of a method to validate arguments:

if (account == null) {
    throw new IllegalArgumentException("Account is required");
}

//Or for strings
if (name == null || name.length() == 0) {   //Or even StringUtils.isBlank() of Apache Commons
    throw new IllegalArgumentException("Name is required");
}

Well, here  are templates that makes it easy to validate an object or string and throw an IllegalArgumentException if it isn’t.

Continue reading

Write a filter loop in 20 seconds using Eclipse templates

We’re still waiting for closures to come to  Java – the saga continues. Until then we’ll need to write the filter boilerplate code  manually. Filter loops often take an input array/collection, match each element with a condition and, if the condition matches, adds the element to another, filtered list. Here’s an example:

List filteredNames = new ArrayList();

for (String name : names) { //names is the original String Collection/array
    if (name.contains("Sam")) {
        filteredNames.add(name);
    }
}

This code is tedious, error-prone and a time-waster. It takes a minute or two or even longer to write without any errors.

You can use Eclipse templates to generate a filter loop in about 20 seconds. If you haven’t worked with templates before, see this post for an overview.

I’ve created a template that produces a List declaration, enhanced for loop, if statement and an add to the filtered list. The list’s type is taken from the nearest array/collection in scope so should be a fairly good match. It even generates import statements for the List and ArrayList.

You can either import the template (recommended; much faster) or create the template manually.

Continue reading

Faster null checking in Java with Eclipse templates

We constantly have to check for nulls in Java. There are ways/ideas to cut down on them (eg. Safe Navigation Operator, type annotations, Null Object, better API design) but they’re either not here yet or not used often enough. So you’ll often need code similar to the following:

Transport transport = SomeAPI.createTransport(...);
//...
if (transport != null) {
    //... Do something with transport...
    if (transport.getSomething() != null) {
        //... Do something with transport.getSomething ...
    }
}

Typing the null-check is fine until you have to retype it 5 times a day, every day for 10 years (well, at least it feels like that).

You can use an Eclipse template to stop the madness. If you haven’t worked with templates before, see this post for an overview.

I’ve created a template that produces an if-statement with a not-null check on a variable that Eclipse will guess at first but give you the option to override it.

You can either import the template (recommended; much faster) or create the template manually.

Continue reading

How to tweak Eclipse templates to suit you

I discussed templates and why to use them in another post. Basically, we use them to eliminate the pesky, repetitive code zombies. I also showed some built-in templates and what they do.

But what if you want to add your own template or modify an existing one? Managing your own templates is important because your business domain and how you work determines to a large extent what is the common code you use all the time.

Don’t be tempted to say “It takes too long to create the template. In that time I could’ve typed the code myself.” Are you going to say that the next 50 times you have to type the same code? I always force myself to sacrifice the 2 minutes because I’ll save me 20 minutes in the long run.

Continue reading

Speed up boilerplate code with Eclipse templates

Take the following piece of code:

for (int i = 0; i < arguments.length; i++) {
    String argument = arguments[i];
    // ... Do something with argument...
}

How many times have you typed out a similar for-loop, mistyped arguments the 2nd time, made a syntax error by forgetting a semicolon, etc, etc. Same goes for writing a main method or a try-catch block. Even typing an enhanced for-loop in the above example is slow.

To me they’re code zombies. Nobody likes them, everybody wants to get rid of them asap and just when you think you’ve killed one, it wakes up again and doesn’t stop… ever.

This is where templates bash in with modified shotguns and spiked baseball/cricket bats. You use templates to rid yourself of these code zombies, because life’s too short and fast to have to write long and slow code.

Continue reading