Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Killing Boilerplate With Lombok Annotations

DZone's Guide to

Killing Boilerplate With Lombok Annotations

Want to see how Lombok can remove your POJOs' boilerplate? Let's dive into what you can do with Lombok annotations to save yourself time and energy.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Project Lombok is a Java library that automatically plugs into your editor and build tools, spicing up your Java program. Never write another getter or equals method again in your POJOs.

Consider the following code block:

public class Employee {
    private String firstName;
    private String lastName;
    private String email;

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {

        private String firstName;
        private String lastName;
        private String email;

        public Builder fistname(String firstName) {
            this.firstName = firstName;
            return this;
        }

        public Builder lastname(String lastName) {
            this.lastName = lastName;
            return this;
        }

        public Builder email(String email) {
            this.email = email;
            return this;
        }

        public Employee build() {
            return new Employee(firstName, lastName, email);
        }
    }
}


The above code block just creates one Java class, Employee, and provides its builder. Clearly, this is a lot of code we have written, no? This won’t stop here, as the number of fields in the class Employee increases, the lines of code will also grow, and we will be left with a big bulky code set. Now consider the same Employee class but with Lombok annotations:

@Builder
@Getter
@Setter
@EqualsAndHashCode
public class Employee {
   private String firstName;
   private String lastName;
   private String email;
}


Yes! That’s all we are required to write. With @Builder over the Employee class, we have created a so-called ‘builder’ aspect to the class. The effect of @Builder is that an inner class is generated named Builder with a private constructor — and its instances are made by using a builder() method, which also gets generated automatically for use.

Apart from @Builder, some other annotations are also very useful when creating a Java class (POJOs) like:

  1. @Getter: This will build a standard getter for every field in the class. In our case, 3 different getters would be created for the 3 fields of Employee class viz; getFirstName(), getLastName(), and getEmail().
  2. @Setter: Similar to @Getter, this will generate the standard setter for every field of the employee class viz; setFirstName(“”), setLastName(“”), and setEmail(“”).
  3. @AllArgsConstructor@AllArgsConstructor generates a constructor with 1 parameter for each field in your class. Fields marked with a @NonNull result in null checks on those parameters.
  4. @NonNull: This is applied on those fields that we want to keep a check on so their values can’t be null — otherwise an exception should be thrown. For example, we can keep a check on the email field that it should not be null for an Employee object:
    @NonNull
    private String email;
  5. @EqualsAndHashCode: As we all know, by default, each and every object in Java would inherit the equals() and hashCode() methods. Using @EqualsAndHashCode will generate the implementations for these 2 methods.

Another very important annotation that we have been using is @Singular. By annotating one of the parameters or fields with the @Singular annotation, Lombok will treat that builder node as a collection, and it generates 2 adder methods instead of a setter method. One adds a single element to the collection, and one adds all elements of another collection to the collection. A clear method is also generated. Annotating a field with @Singular guarantees the following properties:

  1. When build() is invoked, the produced collection will be immutable.
  2. Calling one of the ‘adder’ methods, or the ‘clear’ method, after invoking build() does not modify any already generated objects, and, if the build() is later called again, results in the generation of another collection with all the elements added since the creation of the builder.
  3. The produced collection will be compacted to the smallest feasible format while remaining efficient.

CAUTION: @Singular can only be applied to collection types known to Lombok.

To see the list of collection types supported by Lombok (at the time of writing of this blog) click here

Beauty and IntelliSense of Lombok

If your identifiers/parameters are written in common English, Lombok assumes that the name of any collection with @Singular on it is an English plural and will attempt to automatically singularize that name. If that is possible, the add-one method will use that name. For example, if your collection is called employees, then the add-one method will automatically be called employee. You can also specify the singular form of your identifier explicitly by passing the singular form as an argument to the annotation like:

@Singular("employee") 
List employees;


Also, if Lombok cannot singularize your identifier, or it is ambiguous, Lombok will generate an error and force you to explicitly specify the singular name.

I guess now you understand what Lombok is doing for you behind the scenes — but wait a sec, did your project know that you are going to use Lombok to remove that much boilerplate code? No, you haven’t told your project to go and search for Lombok and use its help. Yes, you guessed it, you would need to add Lombok as a dependency in your pom.xml. Add the following to the dependencies section in the pom.xml of your project:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.16</version>
    <scope>provided</scope>
</dependency>


Once you have added the above dependency, just go and add the Lombok-Plugin to your IDE. I have been using IntelliJ, and you can add Lombok plugin with help from the screenshot I am attaching below:

InstallLombokPlugin

Since I already have the Lombok plugin installed in my IDE, it shows me how to uninstall the plugin. Normally, it asks you to install the plugin instead.

I hope that the above article helps you understand how we can utilize the functionality of the annotations provided by Lombok. Please feel free to comment or contact me if you have any doubts using Lombok, or if you have any questions about it.

Thanks and happy blogging.

This article was first published on the Knoldus blog.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,boilerplate code ,lombok ,annotations ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}