logoNavigate back to the homepage
ARCHETYPER

Lombok

KNSI

·

 
January 29th, 2021 · 4 min read

Lombok: Unhinge Yourself From Boilerplate Code

Overview

Java is a strongly-typed, object-oriented programming language, which often translates to strict request, response, and data-transfer objects. It provides the developer with a clear picture of the data available for consumption in any class, but adds a lot of boilerplate code such as getters, setters, and let us not forget the constructor. Not only is it painful to write and maintain these methods, but they also add clutter to the code. Project Lombok allows us to write clutter-free code with impressive community support.

Highlights

Lombok is a code generator and kicks in during compile time. Before diving deep into the features of the package, let us see how to include them in our configuration files:

1/* Maven */<dependencies>
2 <dependency>
3 <groupId>org.projectlombok</groupId>
4 <artifactId>lombok</artifactId>
5 <version>${lombok.version}</version>
6 <scope>provided</scope>
7 </dependency>
8</dependencies>/* Include in build section of the pom file */<annotationProcessorPaths>
9 <path>
10 <groupId>org.projectlombok</groupId>
11 <artifactId>lombok</artifactId>
12 <version>1.18.16</version>
13 </path>
14</annotationProcessorPaths>/* Gradle */dependencies {
15 compileOnly 'org.projectlombok:lombok:$version'
16 annotationProcessor 'org.projectlombok:lombok:$version'
17
18 testCompileOnly 'org.projectlombok:lombok:$version'
19 testAnnotationProcessor 'org.projectlombok:lombok:$version'
20}

If you are using IntelliJ IDEA, it is advisable to install the Lombok plugin for a better developer experience.

Encapsulation simplified

  • Getters and Setters

    Getters and Setters are an important aspect of encapsulation, they allow the class to decide what data is available to other objects. In contrast, writing Getters and Setters for large classes add to the clutter. Lombok provides the @Getter and @Setter annotation which can be placed at the class or field level. If you want all fields of the class to have the Getters/Setters, then it is advisable to add the annotation to the whole class. Let us look at a standard Student class:

    1public class Student {
    2
    3 private String name;
    4 private String identityNumber;
    5 private Integer grade;
    6
    7 public String getName() {
    8 return name;
    9 }
    10
    11 public void setName(String name) {
    12 this.name = name;
    13 }
    14
    15 public String getIdentityNumber() {
    16 return identityNumber;
    17 }
    18
    19 public void setIdentityNumber(String identityNumber) {
    20 this.identityNumber = identityNumber;
    21 }
    22
    23 public Integer getGrade() {
    24 return grade;
    25 }
    26
    27 public void setGrade(Integer grade) {
    28 this.grade = grade;
    29 }
    30
    31 public Student(String name, String identityNumber, Integer grade) {
    32 this.name = name;
    33 this.identityNumber = identityNumber;
    34 this.grade = grade;
    35 }
    36}

    Now let us add some Lombok magic:

    1@Getter
    2@Setter
    3public class Student {
    4
    5 private String name;
    6 private String identityNumber;
    7 private Integer grade;
    8
    9 public Student(String name, String identityNumber, Integer grade) {
    10 this.name = name;
    11 this.identityNumber = identityNumber;
    12 this.grade = grade;
    13 }
    14}
  • Constructors

    Lombok provides three different annotations to generate constructors for your classes. @AllArgsConstructor adds a constructor for all the fields in the class. Correspondingly, @NoArgsConstructor adds an empty constructor. But what if you want a constructor only for the non-final fields in your class, @RequiredArgsConstructor achieves precisely this.

  • hashcode, equals and toString methods:

    Overriding the toString() and equals() methods are some of the most predictable boilerplate snippets. Interestingly, it can be daunting to standardize them across the codebase. Lombok has provided the @ToString and @EqualsAndHashCode annotations that auto-generate the methods whenever we compile. Both annotations are placed at the class level and allow the developer to include fields from the superclass by passing the attribute callSuper as true.

    So you can simplify a Plain Old Java Object of Student type as shown below

    1@Getter
    2@Setter
    3@AllArgsConstructor
    4@EqualsAndHashCode
    5@ToString
    6public class Student {
    7
    8 private String name;
    9 private String identityNumber;
    10 private Integer grade;
    11}

    However, if you are finding it cumbersome to add @AllArgsConstructor, @Getter, @Setter and @EqualsAndHashCode to every class. You can replace it with @Data, a simple but powerful alias.

Immutability enhanced

Let us first write an immutable class:

1public final class Student {
2
3 private final String name;
4 private final String identityNumber;
5 private final Integer grade;
6
7 public String getName() {
8 return name;
9 }
10
11 public String getIdentityNumber() {
12 return identityNumber;
13 }
14
15 public Integer getGrade() {
16 return grade;
17 }
18
19 public Student(String name, String identityNumber, Integer grade) {
20 this.name = name;
21 this.identityNumber = identityNumber;
22 this.grade = grade;
23 }
24}

We can use the @Value annotation to mark every field in the class as final. It also adds a equals() and hashCode method to the class. Hence, It can be considered as the immutable variant of @Data. We can also make a field non-final by using @NonFinal on top of the field. But it would not be completely immutable though. Our Student class now looks like this:

1@Value
2public class Student {
3
4 private final String name;
5 private final String identityNumber;
6 private final Integer grade;
7}

Do not build builders anymore

The builder pattern is a clean way of building complex objects. Unfortunately, writing builders for every complex or large class feels laborious. Lombok provides the @Builder annotation with an optional toBuilder attribute. If the attribute is set to true, then a method to obtain the builder from the built object will be provided.

1/* without @Builder */public class Student {
2
3 private final String name;
4 private final String identityNumber;
5 private final Integer grade;
6
7 public static Builder builder(){
8 return new Builder();
9 }
10
11 public static class Builder {
12 private String name;
13 private String identityNumber;
14 private Integer grade;
15
16 public Builder name(String name){
17 this.name = name;
18 return this;
19 }
20
21 public Builder identityNumber(String identityNumber){
22 this.identityNumber = identityNumber;
23 return this;
24 }
25
26 public Builder grade(Integer grade){
27 this.grade = grade;
28 return this;
29 }
30
31 public Student build(){
32 return new Student(name, identityNumber, grade);
33 }
34 }
35}/* with @Builder */@Builder
36public class Student {
37
38 private final String name;
39 private final String identityNumber;
40 private final Integer grade;
41}

We can consume the builder class as shown below:

1Student student = Student.builder()
2 .name("unpackaged")
3 .identityNumber("1A045")
4 .grade(9)
5 .build();

Write synchronous code easily

When writing a multi-threaded application, most critical sections are marked with a synchronized block. A sample code snippet is shown below:

1public class Student {
2
3 private String name;
4 private String identityNumber;
5 private Integer grade;
6 private final Object lock = new Object();
7
8 public Integer updateGrade(Integer marks){
9 synchronized (lock) {
10 if (marks > 40) {
11 grade++;
12 }
13 }
14 return grade;
15 }
16}

Managing multiple such lock variables adds to the clutter and may lead to some code smells. We can offload such blocks to the @Synchronized annotation of Lombok. It adds a $LOCK variable to the static and non-static scope of the class if not present and wraps the critical section inside a synchronized block. It allows developers to concentrate only on the business logic. You can also pass a string that would be taken as the lock variable name. The above class would be transformed as shown below:

1public class Student {
2
3 private String name;
4 private String identityNumber;
5 private Integer grade;
6 private final Object lock = new Object();
7
8 @Synchronized
9 public Integer updateGrade(Integer marks){
10 if (marks > 40) {
11 grade++;
12 }
13 return grade;
14 }
15
16 @Synchronized("lock")
17 public String getName(){
18 return name;
19 }
20}

Experimental features

Apart from the above annotations, there are many more code generators available. Lombok follows the canary approach. Initially, a code generator is available in the experimental package. After observing its adoption and bug fixes it is promoted to the main package. Let us look at some interesting experimental annotations in brief:

  • @FieldNameConstants: Creates an inner class with constants for all the fields in the class upon which the annotation exists. It is interesting to note that it does not generate a constant for the methods or one for the class name. It would be better if they could add this to the annotation before marking it stable for use.

  • @UtilityClass: Adds a private constructor to the annotated class and marks all fields and methods in the class as static.

  • @Slf4j: Adds a logger object to the class with the configured logger.

Although these are not as powerful as some of the other generators, they still make the code predictable and less prone to human error such as creating an object of a utility class or configuring the wrong logger for a class!

I don’t want to use Lombok anymore!

If at any point in time you want to remove Lombok from your application, you can use the Delombok tool to generate the boilerplate code and remove the application from the build configuration file. Delombok is available within the Lombok jar file. Developers can run the below command to Delombok their application:

1java -jar lombok.jar delombok <source-direcory> -d <destination-directory>

IDEA also provides an option to Delombok selected files. You can also use the maven plugin to achieve the same.

Evaluation Metrics

CategoryRatingsDeliberations
Ease of useGoodExtremely clear annotations, very good support, does not require any extra packages
CommunityGoodFrequent updates and release, great community interaction, Maintainers tend to open issues as quick as possible
Active usageGoodMore that 12 thousand usages recorded on maven central at the time of writing
VulnerabilitiesGoodSince it is a build-time dependency, it does not have any notable vulnerabilities
Docs and TrainingsAverageDetailed docs covering all use cases, many examples with multiple annotations are not present

Conclusion

We cannot stress enough how much time Lombok has saved while removing clutter that was once common in the daily discourse of a Java developer. Unlike standard annotation processors, Lombok uses internal Java APIs and injects the code into the class. It has hence raised concerns of developers on its stability as Java adopts a faster release cycle. However, if you consider all the advantages and the fact that you can Delombok your code anytime, we can embrace it without concerns. It makes Java code look cool again.

As a community, they are extremely active. Anyone can join their email thread and start a thread on a possible feature or enhancement. They are also cautious on what they deem to be stable, hence, putting any doubt to sleep.

Check out the package and some reading materials

  • https://projectlombok.org/
  • Join the Lombok community at https://groups.google.com/forum/#!forum/project-lombok, participate and contribute to this amazing library.

Disclosures

The content and evaluation scores mentioned in this article/review is subjective and is the personal opinion of authors at Unpackaged Reviews based on everyday usage and research on popular developer forums. They do not represent any company’s views and are not impacted by any sponsorships/collaboration.

Header Photo by David Becker on Unsplash

More articles from Unpackaged Reviews

Papaparse

Zoom through your CSV parsing!

August 15th, 2020 · 5 min read

Moment

A Concise Date Handling Experience!

August 7th, 2020 · 6 min read
© 2020-2021 Unpackaged Reviews
Link to $https://twitter.com/unpakgd_reviewsLink to $https://unpackaged-reviews.medium.com