IT Knowledge from developers for developers

There are libraries and frameworks that belong to the daily tools of a Java developer, e.g. your preferred testing framework or useful libraries like Guava. For some time now, I have used a library that meets three criteria that are essential to my daily work: Project Lombok. It allows me to avoid boilerplate code, it reduces errors, and it plays very well together with other frameworks.

But first, to show you why I’m so thrilled about Lombok, let us have a look at some code that can be found in many Java projects:

One thing which stands out immediately: In Java, you sometimes need quite a lot of code to express very little. In fact, many developers let their IDE generate most of this code, and this is the main problem: Once a class must be changed, you have to write new getters and setters, equals, hashCode, and toString. Of course, this is error-prone, especially if you have to adjust a class under time constraints and pressure.

This is where Lombok comes into play: Only a single annotation (@Data) is needed to make the class look clearer:

Another benefit: Lombok only generates missing methods. If there is a getter or setter in your code that is more specific, you can add it to your normal code. It will then be more noticeable than before.

But Lombok can do even more: Once inheritance comes into play, it is easy to specify whether equals, hashCode, and toString should also take account of fields of the parent class:

Use Lombok in your project

The Maven coordinates (or Ivy and Gradle) can be found on the download page. On this page the IDE plugins, offering Lombok support, are listed, too. These are especially necessary for features like autocompletion.

For Eclipse, it is sufficient to download the latest version of Lombok and execute the JAR. This will open a graphical interface that guides you through the installation process. In IntelliJ the plugin can be installed via plugin management.

So if you like to write less code, give Lombok a try. What are your favorite Java frameworks and everyday helpers and why? Leave a comment and tell more about your tools.