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:

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 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:

@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 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s