Saturday, December 8, 2018

Project Lombok : Boilerplate code reducer

Project Lombok, boilerplate code remover and space saver by generating code in ".class" file instead of generating it in the "source code" file. In this article, I will try to explain how Lombok is so popular and its usage with step by step example.

Introduction :

Project Lombok is java library/tool which is used to minimize boilerplate code and save developers time. No doubt, java is a great language but is criticized by the community for one reason that is verbosity. 

Lombok generates code like getters, setters, toString, and IDE does the same thing for us but IDE generates it in our source code wile Lombok generate it in ".class" file directly.

How to configure Project Lombok to IDE?

Setup with IntelliJ :

                       Step 1: Go to File > Settings > Plugins
                       Step 2: Click on Browse repositories
                       Step 3: Search for Lombok plugin
                       Step 4: Click on install plugin
                       Step 5: Restart IntelliJ IDEA


Setup with Eclipse :

Lombok will operate if we put it in project classpath and for that, we need to do the following steps. 
Step 1: Download lombok.jar from https://projectlombok.org/downloads/lombok.jar
Step 2: To have library version consistency and to avoid version conflicts at project level let's maven do download on our behalf.
Step 3: Create a maven project and add blow mentioned maven dependency in pom.xml.


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

Step 4: After building the project, you will find lombok.jar downloaded in .m2 repository. Copy this jar and paste it to eclipse folder.

Step 5: Open command prompt window and navigate to the location where lombok.jar is copied. Execute command "java -jar lombok.jar". It will open installation wizard like below.


Step 6: Click on "Specify location" button provide the path of "eclipse.exe" as shown in below image.

Step 7: After providing the path, click on "Install / Update" button. This is the last step of installation and will pop up with successful installation completion message like below.

Now our IDE is equipped with Lombok apparatus.

Lombok Annotations

Lombok provides set of annotations out of which some of the annotations we can use in day to day coding. Let's have the look of a few of them.

@Getter and @Setter: 

The @Getter and @Setter annotation provide getter and setter method for a field respectively. These annotations can be used at field and class level.
Encapsulating object properties using public getter and setter methods are common practice in the Java world. Many frameworks rely on this "bean pattern" and therefore IDE also supports autogeneration of getter/setter and constructor code.

Example

Vanilla code (Without Lombok feature)
public class EmployeeWithoutLombok {

private String empId;
private String firstName;
private String lastname;
private Date dob;
private String phoneNo;

public String getEmpId() {
return empId;
}

public void setEmpId(String empId) {
this.empId = empId;
}

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 Date getDob() {
return dob;
}

public void setDob(Date dob) {
this.dob = dob;
}

public String getPhoneNo() {
return phoneNo;
}

public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
}

Code with Lombok annotations.
@Getter
@Setter
public class EmployeeWithLombok {

private String empId;
private String firstName;
private String lastname;
private Date dob;
private String phoneNo;

        // Code required for getter and setter method not required to write.
}

@ToString

This annotation generates toString() method in ".class" file at compile time. No need to write explicit code for toString() method in POJO class. If we use @ToString annotation then we no need to maintain toString() method whenever we enrich POJO properties.

Example

Vanilla code (Without Lombok feature)

public class EmployeeWithoutLombok {

private String empId;
private String firstName;
private String lastname;
private Date dob;
private String phoneNo;

// toString method
@Override
public String toString() {
return "EmployeeWithoutLombok [empId=" + empId + ", firstName="
+ firstName + ", lastname=" + lastname + ", dob=" + dob
+ ", phoneNo=" + phoneNo + "]";
}
}


Code with Lombok feature

@ToString
public class EmployeeWithoutLombok {

private String empId;
private String firstName;
private String lastname;
private Date dob;
private String phoneNo;

}

@Builder

This annotation used to generate the code required to have your class be instantiable using builder pattern.

Example

Code with builder pattern without @Builder Lombok annotation.

package com.kasegvikas.feature2;

import java.util.Date;

public class EmployeeWithoutLombok {

private String empId;
private String firstName;
private String lastname;
private Date dob;
private String phoneNo;

public EmployeeWithoutLombok(String empId, String firstName,
String lastname, Date dob, String phoneNo) {
this.empId = empId;
this.firstName = firstName;
this.lastname = lastname;
this.dob = dob;
this.phoneNo = phoneNo;
}

public static class EmployeeBuilder {
private String empId;
private String firstName;
private String lastname;
private Date dob;
private String phoneNo;

public EmployeeBuilder withEmpId(String empId) {
this.empId = empId;
return this;
}

public EmployeeBuilder withFirstName(String firstName) {
this.firstName = firstName;
return this;
}

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

public EmployeeBuilder withDob(Date dob) {
this.dob = dob;
return this;
}

public EmployeeBuilder withPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
return this;
}

public EmployeeWithoutLombok build() {
return new EmployeeWithoutLombok(empId, firstName, lastname, dob,
phoneNo);
}
}

@Override
public String toString() {
return "EmployeeWithoutLombok [empId=" + empId + ", firstName="
+ firstName + ", lastname=" + lastname + ", dob=" + dob
+ ", phoneNo=" + phoneNo + "]";
}
}

Code with Lombok annotations.
@Builder
public class EmployeeWithLombok {

private String empId;
private String firstName;
private String lastname;
private Date dob;
private String phoneNo;
}

@Log4j, @Slf4j

These annotations are used to generate code related to logger like mentioned in below example.

Code without Lombok annotations
public class EmployeeServiceWithoutLombok implements EmployeeService{

private static final Logger logger = Logger.getLogger(EmployeeServiceWithoutLombok.class);
@Override
public void method1() {
logger.info("In method1 ");
}
}

Code with Lombok annotation

@Log4j
public class EmployeeServiceWithLombok implements EmployeeService{

@Override
public void method1() {
log.info("In method1 ");
}

}

Conclusion :

Reducing boilerplate code benefits in better readability, less code also means less error. Project Lombok is massively used today in almost all the major organizations.

Source Code : 

Examples used in this article are available on GitHub.

No comments:

Post a Comment