April 05, 2010 | Category: Uncategorized

Modern Java: Lombok

In recent months, I’ve been looking at a lot of new Java libraries to see what I’d like to use and what I think still has a way to go. I’ll be posting about them all in due course but I wanted to mention Lombok first.

First, a class:

public class Person {
    private String firstName;
    private String lastName;
    private int age;

    public String getFirstName() {
      return firstName;
    }
    public void setFirstName(String firstName) {
      this.firstName = firstName;
    }
    public String getLastName() {
      return lastName;
    }
    public void setLastName(String lastName) {
      this.lastName = lastName;
    }
    public int getAge() {
      return age;
    }
    public void setAge(int age) {
      this.age = age;
    }
}

The problem here is that everything after public int age is predictable and verbose; you know that this is a Java bean class and that the fields are likely going to have getters and setters just like those provided. If we know exactly what to expect, shouldn’t the compiler take care of that for us rather than having us specify more code? Less code is often cleaner code.

For several years now, people have been asking for the idea of properties in Java. That is, being able to define fields and automatically having standard getters and setters defined, without having to clutter the class file with boilerplate. The most common (and reasonable) response for avoiding this is that it would be difficult to implement without affecting backwards compatibility.

While those proposals are pretty much dead at the moment, Lombok saves us from having to specify our standard getters and setters by marking our classes as beans and then jumping into the compilation process to make sure getters and setters are generated. The above code becomes:

@Data
public class Person {
    private String firstName;
    private String lastName;
    private int age;
}

That’s right: the 18 or so lines of getter/setter boilerplate are replaced by the tiny little @Data annotation, and the code is much cleaner. As a bonus, @Data also generates a toString(), an equals() and a hashCode(). You can use the other Lombok annotations to tweak the behaviour, but this is what most people are going to want.

Also of note is the @Cleanup annotation, which provides automatic resource management (ARM) for using input/output streams. While this will be less essential if ARM arrives in Java 7, it’s a handy little helper for the time being.

While Lombok can’t make bad code good, it can make verbose code a lot more succinct.