Get Rid of the Boilerplate in JAVA with Annotations @Lombok

Table of contents
Reading Time: 4 minutes

Hi all,

we have been programming in Java for quite a while now and came across various scenarios such as those concerning the lines of code, redundant code boilerplate or programming style like moving from imperative style of coding to functional style etc., Java is quite verbose and will require a developer to often write significantly more code for the same task than the other languages.

In this blog, we’ll primarily focus on how to remove this boilerplate from our Java code. We shall see how using annotations from Lombok would help us get a cleaner and simpler code. So let’s get started.

What is Lombok?

The answer is 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 Pojo’s.

Consider the following code block:

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 class Employee increases the line of code will also grow and we would be left with a big bulky code set. Now consider the same Employee class but with the Lombok annotations:

Yes! That’s all we are required to write, with @Builder annotation over the Employee class we 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(POJO’s) like:

  1. @Getter – this will build a standard getter for every field in the class like in our case 3 different getter 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 on which we want to keep a check that their value 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 that by default each and every object in java would inherit the *equals()* and *hashCode()* methods, using @EqualsAndHashCode would 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 which adds a single element to the collection, and one which adds all elements of another collection to the collection. No setter to just set the collection will be generated. 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 this is possible, the add-one method will use this 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 in case 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 would have understood what Lombok is doing for you behind the scenes, but wait a sec did your project has any information that you are going to use Lombok to remove this much boilerplate redundant code? No, you haven’t told your project to go and search for Lombok and take its help :-p Yes you guess it right 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 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 the help of the screenshot I am attaching below:

InstallLombokPlugin

Since i already have Lombok plugin installed in my IDE it shows me to uninstall the plugin but would ask you to install the plugin instead.

I hope that the above article would help 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 doubt using Lombok or if you have any query regarding the same.

Thanks and happy blogging. 🙂 🙂

References:

  1. https://projectlombok.org

 

knoldus-advt-sticker

Written by 

Prashant is a Senior Software Consultant having experience more than 5 years, both in service development and client interaction. He is familiar with Object-Oriented Programming Paradigms and has worked with Java and Scala-based technologies and has experience working with the reactive technology stack, following the agile methodology. He's currently involved in creating reactive microservices some of which are already live and running successfully in production, he has also worked upon scaling of these microservices by implementing the best practices of APIGEE-Edge. He is a good team player, and currently managing a team of 4 people. He's always eager to learn new and advance concepts in order to expand his horizon and apply them in project development with his skills. His hobbies include Teaching, Playing Sports, Cooking, watching Sci-Fi movies and traveling with friends.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading