Lombok: The Good, The Bad, and The Controversial
Lombok/Indonesia - Photo by Koes nadi on Unsplash

Lombok: The Good, The Bad, and The Controversial

Lombok: The Good, The Bad, and The Controversial

Java developers, particularly those coming from other programming languages, have long complained about the overwhelming amount of boilerplate code found in Java codebases. In Object-Oriented Java development, the necessity of ensuring the encapsulation and immutability of objects only adds to the amount of boilerplate code required. This issue is a common pain point for developers and can be exemplified by tens or even hundreds of lines of getter and setter methods per source file, as well as extensive class constructors. In response to this problem, Project Lombok was created.

Lombok

Project Lombok is a java library that automatically plugs into your editor and building tools, spicing up your java. Never write another getter or equals method again, with one annotation your class has a fully featured builder, automates your logging variables, and much more. (from?https://projectlombok.org/)

Basically, Lombok uses?meta-programming?to generate code at compile time. In addition to the possibility of generating getters/setters methods, it can generate equals methods, hash code and a variety of class constructors. Besides the possibility of generating class-level attributes, for instance, a logger attribute using LOG4J. It may seem mysterious, but in fact, Lombok uses two native Java features to generate this code. Let's explore these features below.

How does Lombok work?

Annotations

Annotations were introduced in Java a long time ago, in version 6. And Lombok has a series of annotations that can be used to identify/mark the need to generate new code within that class.

AST (Abstract Syntax Tree)

Abstract Syntax Tree is the way the compiler represents the steps that need to be performed for the final program to be generated. AST Java is a kind of intermediate structure that is created before the byte code is generated. Java has its own AST and it can be manipulated.

No alt text provided for this image
https://sewiki.iai.uni-bonn.de/_media/research/jtransformer/lmp.jpg

So, if we join these two technologies/features everything starts to make sense. During the compilation phase, Lombok annotations are identified and Lombok manipulates AST to insert code that did not exist before into existing classes.

However, Lombok doesn't do this in a snap. It needs to intercept calls to the Java compiler in order to handle the intermediate code that will be generated. This is done through plugins, either in your IDE (IntelliJ, VSCode, Eclipse) or via building tools (Maven/Gradle/Make). If your IDE or your dependency/build manager does not support Lombok your code will not compile.

Considerations

Compilation time

Due to Lombok performing its magic at compilation time, you can expect an increase in the compilation time of your Java project/codebase. And this increase can have a high impact, especially on large codebases, the more code to generate the more AST to handle. The Lombok development team has been working to lessen this impact and has succeeded, but the time is still longer with Lombok than without it.

Java Standards

Let's say you're trying to compile your source code using only javac (the java compiler) and the source code uses a?get?method generated by Lombok in this case you will get a compilation error saying that the?get?method doesn't exist.

It happens because a source code that uses Lombok annotations is not a valid Java source code. (Controversial but sincere)

Is this a problem? The answer is yes and no. Yes, because you will always depend on Lombok plugins for your source code compilation to work. No, because in most cases developers use IDEs or building tools to compile their Java code.

Compatibility

Another point of attention is the compatibility with future and previous versions of Java. With each version, Java may change the way AST is generated and interpreted. In version 8 it can be one way and in version 9 another way. So Project Lombok needs to update its dependency library to generate the code in the most up-to-date way, and of course, maintain backward compatibility as well.

If you are using Lombok, it is possible that your project will fail to compile if you upgrade your Java release.

It's a problem? Yes and no. Yes, because you will only notice that your code stopped compiling after you perform the Java upgrade. No, because Project Lombok usually releases library updates before the final versions of Java. But remember, if you use Lombok be aware of possible future compilation failures for the reason I've described above.

Boilerplate code

This is where Lombok gains popularity, in the emotional and most visible part of the source code. No doubt Lombok drastically reduces the amount of boilerplate code in your Java classes, especially in domain classes (TOs, DTOs, Entities) where usually we have a lot of class-level attributes.

If we count 3 lines of code for each?get?method and 3 more lines of code for each?set?method we will end up having a reason of 6 lines less for each class attribute if you are using Lombok to generate?get?and?set?for all of the class attributes. In a class with 10 attributes, you will save 60 lines of code minus the lines containing Lombok annotations. Besides equals, hash code, toString and other methods.

That is good? Yes and no. Yes, because your source code file will be smaller, and simpler, and for instance, if you add a new attribute the boilerplate code related to that attribute will be generated automatically. No, because all IDEs, from the simplest to the most complete, can generate this boilerplate code with one or two clicks.

Concluding

Lombok has its advantages, but it also has its drawbacks. A major issue in my opinion is that it can make your code?less readable, especially for developers who are not familiar with Lombok's annotations. This is because the annotations can hide what the code is doing, and may make it more difficult for other developers to understand what is happening behind the scenes.

Another potential drawback is that Lombok is not supported by all IDEs out of the box, which can make it more difficult to set up and use. And Lombok doesn't always play nicely with other libraries or frameworks, which can cause compatibility issues and make debugging tricky and longer.

Despite these, Lombok can be a powerful tool for simplifying your code and reducing boilerplate. It's up to you to weigh the?pros and cons?and decide whether or not it's worth using this library in your project. Ultimately, whether or not to use Lombok comes down to a matter of personal preference and what works best for your team and your project.

Personally

In my personal experience, I tend to avoid using Lombok in my projects. When discussing this topic with my team, I share the points mentioned in this post, and we make a decision based on the project requirements and context. In some Java teams, we've used Lombok, and in others, we haven't, without any negative impact on the project. One noteworthy project I worked on in recent years did not use Lombok, yet it was still very successful. The decision to use Lombok or not depends on a variety of factors and should be evaluated on a case-by-case basis.

The clear advantage is having less code to maintain. However, this type of code (boilerplate) is not considered critical and can be easily generated by your favourite IDE. And the drawback is adding more complexity to your codebase, especially on the project building time and compatibility with future Java versions.

Some of the use cases for using Lombok can be tackled by using Java Records,?check my other article.

Lombok will not determine the success or failure of your project. But if you need to decrease the size of your Java classes Lombok can be helpful. But don't forget to take into account the points that were listed here.

This article was originally published on my personal tech blog and you can find it using this link.

Nadav Smilansky

Software Architect and Team Leader

7 个月

With Kotlin, Lombok is not needed

Jorge Rafael Toselli

Senior Software Engineer / Technical Leader

8 个月

And I can continue: promoting annotations from attributes to constructor params require additional configuration in lombok.config file, and there are some cases where the annotation cannot even be used (it depends on the @Target() setup), and no error will be raised so you can realized your constructor parameter is not being applied with the annotation you have put to the attribute!. I would only use it to add constructors that don't need to add defensive code to prevent incorporating mutable content, for example. I also find @NonNull annotation pretty nice, but.... there's nothing else. If you want to generate good DTOs, I would rather go with records or adding kotlin compiler to your project and use data classes so you can interoperate with them from Java (and of course! why not starting getting rid of all of your java code and start using kotlin!)

Jorge Rafael Toselli

Senior Software Engineer / Technical Leader

8 个月

More critical problems are, for example: `@Data` annotation with huge amount of attributes and no additional annotations will produce equals / hashCode methods that might even not work as expected and with performance problems (and if you want to carefully pick which attributes should be used to generate equals/hashcode you might end up having even more boilerplate/work to be done than generating them with an IDE), generated setters/getters might incorporate/expose mutable content (if used with typical mutable classes like ArrayList, HashSet, java.util.Date to give some examples), StackOverflowError's in equals/hashCode if you map bi directional relationships. And you don't usually test what lombok generates (but you should!!!). And you can easily fall into the group of people that doesn't customize and rely on defaults like only using @Data / @Value instead of customizing them by adding extra annotations. And if you belong to the group of people that adds extra annotations to make your code more robust, you might realize you are changing java-coding complexity by the complexity of configuring a non-standard framework that might not be that natural for you as a Java developer.

Ronald Partridge

Management Consultant and Enterprise Architect

1 年

I use Lombok. I also know many people that won't use it but their reasons are more idiosyncratic than practical. The productivity gains from code reviews are amazing when using Lombok and it's very mature and stable at this point.

要查看或添加评论,请登录

Felix Coutinho的更多文章

  • Mentorship is a Marathon

    Mentorship is a Marathon

    TL;DR: Mentorship is a long-term journey, not a quick fix. There’s a common misconception that getting a mentorship can…

    4 条评论
  • Designing cloud-native microservices [Talk][Deck/References/Links]

    Designing cloud-native microservices [Talk][Deck/References/Links]

    Hello fellow developers and architects! As we venture into the world of cloud-native microservices, I have compiled a…

  • You should stop using Spring @Autowired

    You should stop using Spring @Autowired

    Or "Why you shouldn't use Field Injection when using Spring". TL;DR Injecting beans directly into fields using…

    27 条评论
  • The Highly Standardized Code Syndrome

    The Highly Standardized Code Syndrome

    Dear reader, this article is about a theory under construction and it's been improved and nurtured over time by me…

    2 条评论
  • Creating Effective Code using Java Records

    Creating Effective Code using Java Records

    Java Records is a new feature introduced in Java 14 to make it easier for developers to create immutable classes. A…

    1 条评论

社区洞察

其他会员也浏览了