Getting started with project lombok

Posted By : Anil Kumar Maurya | 31-May-2019

Java contains the boilerplate code in many places which looks a little bit messy sometimes. This can be removed by a bunch of annotations. Lambok generates boilerplate code in the background and helps to keep your code clean. Less boilerplate code is more concise code and easy to maintain. There are many places where we can add annotations to remove the boilerplate code.


1. Local Variable Type Inference: val and var

Many languages assume the local variable type by looking at the expression on the right-hand side of the equals. In Java, it is only possible with the help of Lombok. This is now supported in Java 10 or above. The code snippet below shows how typically we define the local type:

final Map<String, Integer> myMap = new HashMap<>();
map.put("John", 21);

In Lombok, we can write this code by using val as follows:

val myMap = new HashMap<String, Integer>();
myMap.put("John", 30);

val creates a variable that is final and immutable. We can create a mutable local variable by using var.

 

2. Null check

For most of the cases, we check for the null arguments especially if the method forms an API being used by other developers. If the arguments are more the code for null check also increases. We can see this in below example-

public void nullCheckDemo(Employee employee, Account account){
    if(employee == null){
      throw new Exception("Employee is null");
    }
    if(account == null){
      throw new Exception("Account is null");
    }
// core logic
}

The above code for the null check can be removed by marking the parameters with @NonNull. Lombok produces a null check for that parameter on your behalf.

public void nullCheckDemo(@NonNull Employee employee, @NonNull Account account){
      // core logic
}


3. Cleaner Data Classes

Apart from the above features, we can use below annotations to remove the boilerplate code from our application-

@Getter - Getter methods for private member variables
@Setter - Setter methods for private nonfinal member variables
@AllArgsConstructor - A constructor (without or with arguments)
@ToString - toString method to help with logging
@EqualsAndHashCode - equals and hashCode (dealing with equality/collections)

 

Thanks

About Author

Author Image
Anil Kumar Maurya

Anil is an experienced Lead with core knowledge of Java, Spring, and SQL. He has good working experience in banking, finance and trading domain.

Request for Proposal

Name is required

Comment is required

Sending message..