Using formatter exclusions with Eclipse

@ Nov 06, 2017 21:56:56 ()

Sometimes when you are formatting your code in Eclipse, you may want to prevent some parts of the code from being formatted. Especially when using Java 8 lambdas and optionals.

Here’s some code before being formatted by Eclipse’s default formatter rules.

Code adapted from: blog post Java d’eau ‐ Java 8: Streams in Hibernate and Beyond

session.createQuery("SELECT h FROM Hare h", Hare.class)
    .stream()
    .filter(h -> h.getId() == 1)
    .map(Hare::getName)
    .forEach(System.out::println);

Then after formatting.

session.createQuery("SELECT h FROM Hare h", Hare.class).stream().filter(h -> h.getId() == 1).map(Hare::getName)
                .forEach(System.out::println);

Which doesn’t look very appealing, ay? You can change this behaviour at least in two ways. The first by telling the formatter to ignore this block, through a special formatter tag in your code.

First you need to enable this feature in Eclipse, as it is disabled by default. This setting is found in the preferences JavaCode StyleFormatterEditOff/On Tags.

A screen shot of Eclipse formatter settings
Enabling formatter tags in Eclipse

Then formatting the following code won’t change a thing in the block surrounded by the formatter tags.

/* @Formatter:off */
session.createQuery("SELECT h FROM Hare h", Hare.class)
    .stream()
    .filter(h -> h.getId() == 1)
    .map(Hare::getName)
    .forEach(System.out::println);
/* @Formatter:on */

But having to type these tags can become annoying, and cause more commits and pull requests to be unnecessarily created. So an alternative approach can be to change the formatter behaviour globally.

This can be done in Eclipse in another option under the formatter options, JavaCode StyleFormatterEditLine WrappingFunction CallsQualified invocations.

You will have to choose “Wrap all elements, except first element if not necessary” under Line wrapping policy. And also check “Force split, even if line shorter than maximum line width”.

A screen shot of Eclipse formatter settings
Enabling custom formatter behaviour globally

Once it is done, your code will look like the following no matter what.

session.createQuery("SELECT h FROM Hare h", Hare.class)
    .stream()
    .filter(h -> h.getId() == 1)
    .map(Hare::getName)
    .forEach(System.out::println);

Happy coding!

♥ Open Source