The Art of avoiding boilerplate code: Using lombok library wisely.

William Custódio
3 min readFeb 11, 2020

--

So, let’s write one more paper talking about the usage of Lombok ? Taking as base several other ones I think it is an already defined battle. The usage of lombok has its pros and cons and as engineers we should know how to measure them. Languages like Kotlin already provide ways to escape from boilerplate code, and one of them is the concept of Data Class, simplifying the amount of code used to define a simple class that holds data.

Should I use Lombok or not? It totally depends on the scenario that you are in. For instance, a good scenario for taking into consideration the usage of it would be when there is a simple Bean full of dummy lines of code like the following:

The solution for removing the boilerplate code would be introducing Lombok’s annotations @Getter and @Setter. The result can be seen below:

However, here comes one question, how can I debug the methods now? Since they are only simple getters and setters it would not be necessary to have breakpoints inside of the methods to verify it, we would only need to verify it via our lovely IDE console.

Although the previous examples fit very well with Lombok, there is another scenario that might be tricky; continuing with the same example, we could have the necessity of having an immutable object, such as:

Which could be easily modified to the Lombok approach using the @Value annotation. Basically, Lombok will create a constructor containing as arguments all the final fields together with their getter, toString, equals and hashCode methods. Please, see below:

In my point of view, it would be an issue for specific scenarios where you need to verify via debug mode the usage of a constructor. One example would be when there is an IoC container with multiple beans being directly or indirectly inherited from the same class. If that is the case, I would rather not opt for Lombok and write the code.

Conclusion

Java is a very mature language which has several years in the market and probably will take time for it to incorporate sugar syntax features like Kotlin’s Data Class. Lombok would be an answer for those missing features, however, it requires us to verify if it fits with our current scenario. Finally, it is just one more library created by developers to solve issues that is being faced by several others.

--

--