Lombok in Java – Write Less and Better Code

In Java, it requires a lot of boilerplate code than any other language. And that’s the weak point of Java where anyone can easily hit. More the repetition of the code more time will be consumed. But to fight against the weakness there is a java library called Lombok. Lombok is one of the tools that we refer you to use it. It’s really like unimaginable to code in Java without having Lombok. Here in this article, you will surely find out why Lombok in Java.

Lombok in Java

Lombok is a Java library that helps us to avoid writing the unalterable code that is used in Java which is also known as boilerplate parts of the code.

The java library, Lombok automatically plugs into the editor and build tools. It literally spices up the java programming creating ease while programming.

With the Lombok tool in Java, you never need to write another getter or equals method. Just with one annotation, your class has a fully featured builder. And you get automated logging variables, and much more.

How does Lombok work?

Lombok has various annotations that can be used within our code and has to be processed during the compile time. And on the basis of annotation used appropriate code expansion would take place.

The only thing that Lombok does is, it reduces code in view time and after compiling, the bytecode is injected with all the boilerplate. That is once all the processors finish their work, the compiler generates the bytecode that is understandable to Java Virtual Machine. Lombok helps to keep our codebase small, clean and easy to read and maintain.

Lombok being an annotation processor, it also has the full access to the generated source tree. Usually, annotation processors generate new source files but Lombok modifies existing ones by adding new fields or methods.

How to Install Lombok?

To install Lombok, first, you have to download the latest Lombok version from https://projectlombok.org/download.html or by using Maven, Gradle or other tools.

We will create a maven project in eclipse and just add below Lombok dependency in the pom.xml file.

You need to add below dependency in your maven project so that it got downloaded first in your local repository.

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>

Now you have to do use mvn clean install command. Once the jar is downloaded in the local repository, then go to the downloaded location from the command prompt and execute a command in terminal like this: java -jar lombok-1.16.18.jar.

It will open a small window and Eclipse Installation location can be specified which is usually found automatically and Lombok can be installed.

How to write less with Lombok?

Example:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@ToString
@Table(name = "/make")

public class MakeEntity {
	@Column(name = "id")
	private Long id;
	@Column(name = "name")
	private String name;
	
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="Dealer_table")
	private DealerVehicleEntity dealerVehicleEntity;
}

Here are the reasons why you will have to Write Less Code Using Lombok:

No to repetitive codes

Java makes you write the same code again and again for same common tasks or for the compliance with some framework practices.

It doesn’t give you any benefit writing the code again and again in programs and this is the main reason, why you will need Lombok and why Lombok is created. Lombok makes you free from reluctant repetitive codes and yourself more productive.

Lombok works by plugging into your build process and auto-generating Java bytecode into your .class files. It works on how many Lombok project annotations you have introduced in your code.

You can use getters/setters annotations

Getters/setters annotations can be used either at the field or class level. If you want fine-grained control then you can use it at field level. If it is used at the class level all the getter/setters are created. It is common practice to encapsulate object properties via public getter and setter methods.

And there are lots of frameworks which rely on “Java Bean” pattern extensively that is a class with an empty constructor and get/set methods for “properties”.

Most IDE’s support auto-generating code for these patterns, however, this code needs to live in your sources and also be maintained when a new property is added or a field is renamed.

By adding the @Getter and @Setter annotations in the programme we tell Lombok to generate these for all the fields of the class. And the NoArgsConstructor will generate an empty constructor. Lombok can easily generate the constructors. It can generate both no arguments and with fields.

For that, we need to add annotation @NoArgsConstructor to generate the implicit no argument constructor and @RequiredArgsConstructor to add required field constructor and to make a field required, add @NonNull in the field itself.

Equals, hashCode and toString annotations

The hashCode() and equals() methods while creating a class are recommended to override. Here we have @EqualsAndHashCode annotation which injects code for equals() & hashCode() method which go together in Lombok. And in Lombok, a @ToString annotation provides a toString() implementation.

We can now create Person class without any boilerplate code with help of Lombok annotations. However, for betterment, we can use @Data to replace all the annotations used in the above class and get the same functionality.

Design Pattern-based and automate objects composition Annotations

You can automatically produce the code using @Builder which required to have your class be instantiable using builder pattern. We can tell Lambok tool to generate a builder pattern, preventing us to write an extra Builder class and associated fluent setter-like methods by simply adding the @Builder annotation to our ApiClientConfiguration.

And the @Delegate creates delegate methods which forward the call to this field on which annotation is used.

Checked Exceptions Burden

There are many Java APIs which are designed to throw a number of checked exceptions client code and is forced to either catch or declare to ‘throws’.

You want to avoid those code patterns because it won’t be good with the compiler so you need to use the aptly named @SneakyThrows.

Ensure Your Resources are Released

The try-with-resources block in Java 7 is released to ensure your resources held by instances of anything implementing java.lang.AutoCloseable is released when exiting. For this Lombok provides an alternative way to achieve this. Which is also more flexible via @Cleanup. You can use it for any local variable whose resources you want to release. There is no need to implement any particular interface for them, you’ll just get its close() method called.

Annotate To Get a Logger in your Class

We mostly add logging statements to our code by creating an instance of a Logger from our framework of choice like SLF4J. Lombok have simplified this common pattern and it has many logging frameworks supported and you can also customize the instance name, topic, etc.

Thread-Safer Methods to Write

You can use the synchronized keyword to implement critical sections in Java although it is not a perfectly safe approach. Using the synchronized keyword other client code can also get synchronize on your instance, which might lead to unexpected deadlocks.

This is why Lambok has created @Synchronized, which can annotate your both instance and static method with it. You’ll get an autogenerated private, unexposed field which can be used for locking.

Delomboking

Rolling Lombok Back?What if you wanted to roll back the decision of using Lombok after using it in one of your projects? You might have a large number of classes annotated for it so how can you rollback? For those who want to rollback from using the Lombok, the good news is there is Lombok tool from the same project which can get you autogenerated source code on delomoboking.

You get the Java source code with exactly the same features from the bytecode Lombok built. You do not need to depend on Lombok after you because you can simply replace your original annotated code with these new delomboked file.

Conclusion

There are still a few more features which are not included in this article. Lombok is a useful tool in Java which can helps programmer for fast and easy coding. And there are many customization options you may find useful to get the tool to generate things.

The available built-in configuration system could also help you with that. Lombok helps to get rid of some repetitive code and also it can do some extra things as well. You can feel this article on the usefulness of Lombok tool as motivational to code using this tool whenever applicable.

Leave a Reply

Your email address will not be published. Required fields are marked *