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.

Import the template

Download the templates below then import them into Eclipse.

Create the template manually

Alternatively, create the template with the following settings.

Name ifnotnull
Context Java statements
if (${var} != null) {

Check out the overview of variables if you’re unsure of what the code means.

Related Tips

Support Eclipse On E

Comments are closed.