Effective Java with Project Lombok

What is Project Lombok?

Project Lombok is a really useful tool to reduce boilerplate code in Java programs. It helps you to get rid of standard get/set/equals/etc. methods in your Java classes. Also, it can help you with builder pattern (it’s actually just one annotation and your builder is ready).

Project setup

Maven

Add following dependency to the pom.xml file:

<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.2</version>
</dependency>

Gradle

Add following line the the build.gradle file:

compile 'org.projectlombok:lombok:1.18.2'

Data classes

Imagine you have User entity in your domain. In standard Java program your class will look similar like this:

package com.jakublesko.lombok.article;

import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
import java.util.Objects;

@Entity
public class User {

    private String firstName;

    private String lastName;

    @NotNull
    private String email;

    @NotNull
    private String password;

    private Boolean active;

    public User() {
    }

    public User(@NotNull String email, @NotNull String password) {
        this.email = email;
        this.password = password;
    }

    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 String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Boolean getActive() {
        return active;
    }

    public void setActive(Boolean active) {
        this.active = active;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(email, user.email);
    }

    @Override
    public int hashCode() {
        return Objects.hash(email);
    }

    @Override
    public String toString() {
        return "User{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", active=" + active +
                '}';
    }
}

That’s a lot of code for just 4 data fields. You can reduce this boilerplate code with a few Lombok annotations to something like this:

package com.jakublesko.lombok.article;

import lombok.*;

import javax.persistence.Entity;
import javax.validation.constraints.NotNull;

@Data
@Entity
@RequiredArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class User {

    private String firstName;

    private String lastName;

    @NotNull
    @EqualsAndHashCode.Include
    private String email;

    @NotNull
    @ToString.Exclude
    private String password;

    private Boolean active;
}

I hope the code is self explaning. Just a few notes:
@Data annotation automatically generate getters and setters, eqals(), hashCode() and toString() methods and also it will create constructor with all required fields.
@EqualsAndHashCode.Include means only email field will be used in equals() and hashCode() methods.
@ToString.Exclude means that password field will be excluded from the toString() method.

Builder pattern

Builder pattern is my favorite approach to create instances of data entities. With Lombok you can use @Builder annotation on your data classes and everything is ready.

@Builder // Automatically creates builder
/*...*/
public class User {
    /*...*/
}
package com.jakublesko.lombok.article;

import org.springframework.stereotype.Service;

@Service
public class UserService {

    public User createUser() {
        return User.builder()
                .firstName("Jakub")
                .lastName("Leško")
                .password("MySecretPassword")
                .active(true)
                .build();
    }
}

Conclusion

There are some JVM languages without a necessity to write mentioned boilerplate code (e.g. Kotlin or Scala). But some of us prefer plain old Java and suddenly Lombok can be your swiss knife of effectivity.

You can find full documentation and all available features on lombok office site https://projectlombok.org/.

Leave a Reply

Your email address will not be published. Required fields are marked *