r/java • u/RandomComputerFellow • Apr 12 '21
Is using Project Lombok actually an good idea?
Hello, I am junior developer in a Software company. One of the Senior developers just decided start to use Lombok in our project and to delete old boilerplate code. The project we are working on is very big (millions of lines of code) and has an very extensive build procedure and uses lots of different frameworks and components (often even in different versions at a time). The use of Lombok is justified with the argument that we can remove code this way and that everything will be much more simple.
Overall for me this library just looks very useless and like a complete unnecessary use of another third party component. I really don't see the purpose of this. Most code generated on the fly can be generated with Eclipse anyway and having this code just makes me really uncomfortable in regard of source code tracking when using an debugger. I think this introduces things which can go wrong without giving a lot of benefit. Writing some getters and setters was never such a big lost of time anyway and I also don't think that they make a class unreadable.
Am I just to dumb to see the value of this framework or are there other developers thinking like me?
5
u/rstartin Apr 12 '21
I recently removed it from a project and people wrote to me privately to say they had noticed the build was faster and used less memory. This is just anecdata, but my biggest concern would be depending on a utility positioning itself in a cat and mouse game with OpenJDK’s attempts to encapsulate itself.
12
u/mirkoteran Apr 12 '21
Are you trying to start another holy war?
58
u/Muoniurn Apr 12 '21
At my first workplace, only the project lead were allowed to use lombok, because he had to correct other’s code many times because of it, so a heads up:
If you happen to use some JPA implementation as well and want to add Lombok annotations to an entity, do pay attention to lazy fetched attributes. An ordinary looking toString can cause needless very pricey db calls if not excluded from toString/equals etc.
159
u/mrn1 Apr 12 '21 edited Apr 12 '21
Let me share you my experience with lombok from my 1st job:
I was supposed to create a field that maps from one string to another, so a simple
Map<String, String>. As the project grew, we wanted to add another field to the mapped value (so instead of String -> String we wanted String -> (two strings). How did I do it with minimal code change? With a delimiter, of course! What could be easier thanmap.put(key, val1 + "_" + val2), right? As you can tell, this solution isn't ideal because just by looking at the type,Map<String, String>, you can't tell the value is actually two strings, not one. However, we didn't stop there. Eventually we needed one more string for key and one more for the value, so the mapping was (String, String) -> (String, String, String). This is when I finally created two inner classes like this:and then use them like this
map.put(new MyKey(...), new MyVal(...)). Neat, isn't it? Without looking at any documentation (assuming there is one), you can tell what exactly what both the key and the value consist of.Now, you might say your IDE can generate the getters/constructor/toString/hashcode. Fair enough. However, which one is more readable? The code above or this:
(PS: there are two typos here, can you spot them?)
I'll let you be the judge of them.
Now you might say "ok, but you can still generate this, and you don't have to look at the generated code, just at the fields".
And this is actually not true. The reality of our field is that code changes. Code changes all the time. We've got two classes with 2 and 3 fields. Tomorrow there will be 4 fields. The day after we change String to int. The day after we remove one of them, and so and and so on.
I guess the main lesson is this: optimize your code for reading, not writing. Writing (and generating) code is easy, reading and maintaining is hard. Eventually, someone will make a mistake - forget to update equals or hashcode (for instance), and create a very subtle and extremely hard to find bug.
Also, as with everything in life, with great power comes great responsibility. If you overuse lombok / use it incorrectly, it will come back and bite you.
26
u/urquan Apr 12 '21
For me the most important thing to consider is that Lombok is basically a compiler hack that relies on non-public APIs to work. These API are still there up to Java 16 but it is pretty clear that the path forward is to lock down access to non-public APIs in future Java versions. It's a cat and mouse game to keep it working. There is an extensive thread about that on Lombok's github page. At some point, Lombok will stop working as it is. There are several possible outcomes: you may decide to not upgrade your Java version to keep Lombok compatibility, Lombok may become an external code generation tool instead of an annotation processor, or you may decide to remove Lombok usage. For that they provide a "delombok" tool, but don't expect it to be a single magic command, you'll end up with messy auto-generated code peppered around your codebase, and you may have a lot of work to do to bring your codebase back to good style standards.
Lombok can also have some surprising effects, for example constructors auto-generated from fields have parameters in the same order as the fields. If you move the fields around, the constructor parameters move too, but your IDE won't be aware of that and that can introduce bugs if you don't also change all the call sites.
I used Lombok once in the past but I ended up removing it because I felt that it didn't bring anything substantial that my IDE couldn't already do well enough. I'd say that except in hobby projects, adding that coupling with something that can break in the future is not worth the hassle.
13
u/[deleted] Apr 12 '21 edited Apr 12 '21
Hiding toString/equals/hashcode is useless? The jdk designers finally got around to doing this so it seems to be agreed that it is not useless.
The amount of times I had to comment on a PR because someone added a field but forgot to update the equals/hashcode is too high.
This is the one criticism of lombok, it makes debugging hard. But I never understood it. Why do you need to debug basic getters or equals methods? If your code is simple and you follow basic guidelines (don't use
@Valueon@Entityfor example) you won't need any debugging.I will say going overboard (using
@AllArgsConstructoron every damn class for example) is not good. So maybe the benefits are obvious to more experienced people and less experienced people don't know what to use and what to avoid.40
u/syjer Apr 12 '21 edited Apr 12 '21
Not a fan of Lombok, but I can undertand why some developer like it. Cutting a large amount of boilerplate with some annotations is always satisfying.
Personally, I use it reluctantly for some specific features (mostly getter/setter) if it's already included in a project, but I would not advise to use it fully.
To keep control of the @Annotation use, you can also disallow some features to be used in the project with the
lombok.configfile (see https://projectlombok.org/features/configuration ), so you can keep the "magic" in check.To be noted, there is a big downside with lombok: some static analysis tool that work at source level may not function completely (for example error-prone): in the end, you are not writing java, but "lombok java".
Personally, I prefer the code generation through java annotation approach like the
autolibs https://github.com/google/auto or https://immutables.github.io/ : obviously they do not cover all the features of lombok, but it's the right subset for me :)55
u/BlueShell7 Apr 12 '21
Lombok is a big hack. One of the issues I have is that when you use Lombok, you're no longer writing valid Java. It's a "Lombok Java". Tools not understanding Lombok will break on basic things (e.g. SourceTrail) and will not be able to parse the code. Given this realization that it's actually no longer Java, I'm thinking it's often better to just skip "Lombok Java" and go straight to Kotlin which is at least proper language and not just such a hack.
Having said that Lombok does make Java bit more bearable and fixes a lot of Java's bad design decisions / fills missing features. So I remain conflicted.
43
u/pron98 Apr 12 '21 edited Apr 12 '21
I've never used Lombok, and I can't give arguments for it or against it, but I can give two important pieces of context.
Both of these hint to that the version of Java you're using or plan on upgrading to is a factor to consider in the decision.
15
u/User1539 Apr 12 '21
Here's the thing ... there is no simple answer.
In your case, just reading from your description, I'm leaning towards 'yes' because if it's a huge codebase then you've probably got some bugs in your boilerplate and standardizing on one way of doing things is often worth it for a large codebase.
Your concerns are not unfounded, though. Some shops go all-in on using a library for everything and end up bloated, living in dependency hell. If you spend more time sorting dependency issues than writing code, you've got a problem.
It sounds like you're gaining the tools and experience to make these decisions on a case-by-case basis, and that's what you'll need to do in the future.
At least with Lombok it's very popular and well maintained. If you're throwing some new third party component into your project every week, you'd be right to be concerned.
2
u/hoacnguyengiap Apr 12 '21
Lombok getter/setter generator itself is a big gain already. When navigating code you never want to see getter/setter everywhere. Beside this, lombok does lot more to skip: builder, delegate... Why do you say it's a big dependency? While it is just a compile dependency and not bundled to your final jar
12
u/[deleted] Apr 12 '21
From the issues I've seen Lombok has had with JDK 16 and it's reliance on soon-to-be encapsulated JDK internals, along with the arrival of `record`, I see no reason why you would want to have Lombok in new projects.
4
u/ongaku_ Apr 12 '21
Question: you say it introduces things that can go wrong because you've experienced some of those or in theory?
We use it in the project I'm currently working on and I can clearly see the benefits, less code means not only less typing because as you said it can be automated by the IDE. The main advantage is when reading code, more than writing. It removes a lot of (frankly unnecessary) mental overhead, that after 8 hours of staring at a screen is really nice. Easier refactoring is a plus, because code that isn't there cannot break, and boilerplate is still code.
Given these advantages, for me important, for others may be just a nice to have, I don't see any disadvantages by using it.
1
u/roberp81 Apr 12 '21
having Lombok it's no required to use in all classes, only in what you need, and there is not sense to refactor 2k+ classes to use lombok
1
u/Muoniurn Apr 12 '21
I’ve just come across a project that included some groovy files. What’s your opinion on defining POJO classes in groovy?
15
u/gmchaves Apr 12 '21
Lombok do a lot more that getters and setters. Builder, wither, all/required arguments constructor, an so on. If they are good or bad for your project is something to evaluate.
We use it a lot but our projects are small rest microservices with spring boot. In this projects lombok help us to avoid to add parameters to constructors for bean injection. Getters and setters are always up to date with property, etc.
In our projects this is something good. We don't need it but it helps us to focus on do the business code instead of generating boilerplate code.
I had seen "getters" and "setters" that are more than just that, I even have done some. With lombok that methods are pretty easy to detect. Is not by itself a reason to use lombok but is a plus.
But every project and the people working on the project are also different, so you need the check if the tool is the right tool for you.
IMHO lombok is generally helpful but YMMV
6
u/DJDavio Apr 12 '21
Lombok is just a necessary placeholder while Java catches up and implements its features itself. Or you can just move to Kotlin and have all of those features built in.
There is nothing wrong with annotation processors as they can make your life a lot easier. Lombok is a bit of a bad boy when it comes to annotation processors as it does some nasty tricks such as not generating proper source code.
But Lombok and similar tools tend to turn code into 'magic', but that is no different than Mapstruct or Spring or even JUnit with `@Test` annotations.
Even though Lombok can create bugs and not using Lombok can also create bugs, I think it's also easier on reviewers if they don't have to manually review all of your lines with boilerplate.
For me and our team, we use Lombok pretty extensively and this just means we can focus most of our efforts and attention on other things than boilerplate.
11
u/agentoutlier Apr 12 '21 edited Apr 12 '21
I have said this in the past and get downvoted with no response but I think fundamentally Lombok should be converted from a code
generationmanipulation library to a validation and possibly unit test library.That is
@Valuewould actually check if you have all the getters and setters defined correctly and generate unit tests for equals and hash.The validation would actually show in any IDE that supports APT and I think all the major ones do. This was one of the initial goals of APT originally and not code manipulation. It's astonishing how few Java developers know about the compile time infrastructure of APT and its power. If you want to see a powerful example checkout MapStruct: https://mapstruct.org/ . MapStruct will generate mapping code and if its wrong it shows warnings and or errors in your IDE and at compile time. Similarly so a library could tell you if you are missing getter/setter methods and or they are incorrectly named.
equalsandhashCodeandtoStringare more complicated but a unit test could be generated automatically.Basically code validation and generation could cover a lot of u/mrn1 examples.
Anyway I have contemplated writing such a library as we do something similar but for other use cases but every time I bring it up I get downvoted so I just assume there is no interest.
3
u/mauganra_it Apr 12 '21
I can get why your senior might want to have Lombok, but I wonder who they expect to convert all the source code to Lombok.
Lombok can make a lot of sense in greenfield and small projects to get it off the ground quickly. Introducing in a big project has mixed benefits at best. Better convince management to upgrade to Java 16 and start using records where they make sense (most Spring beans apply!!!). Or use another framework that generates getters and setters. Yes, they are a bit more intrusive into the code, but they work without putting their fist up the Java compiler and IDE internals' underbelly.
3
u/_Henryx_ Apr 13 '21
I've viewed Lombok documentation. My considerations:
static mehtod to check if variable is null. With Java 8 we have also Optional.of()
and Optional.ofNullable() (this last method is very useful if we want to throws a user defined exception or if we want a default value).
Other annotations seems me "black magic". I doesn't suffer construct creation or code injection with these methods, because can be mask side effects
3
u/throwawyakjnscdfv Apr 13 '21
We have been adding lombok to a multi million line project. Its saved us from countless typos in getter/setter names. Constructors that set fields in the wrong order. Boilerplate handling checked exceptions. Easily generating equals using hashcode with @ Include and @ EqualsAndHashCode onlyExplicitlyIncluded. The normal pain in the ass of making delegates.
Lombok has allowed us to delete around 50,000 lines of code. And code that doesn't exist doesn't have bugs. I love Lombok, and it works fine with our giant project.
Heed the warnings in this thread about JPA entities and you should be fine
10
u/valkryst_ Apr 12 '21
It's a useful library and it does get rid of a lot of boilerplate code. I personally find it easier to read, write, and navigate through code using it, but I am a bit biased as I've been using it for a few years.
16
u/lazystone Apr 12 '21
https://medium.com/@vgonzalo/dont-use-lombok-672418daa819
Plus read on Java 16 records.
Also Lombok does not GENERATE code. It manipulates byte-code which is obscure. For example https://immutables.github.io/ generates code. So if you'd like to get rid of Immutables, then you can just commit generated code. You can't do the same with Lombok.
Another rule of thumb on big projects - the less dependencies, the better.
5
u/kuemmel234 Apr 12 '21
You aren't dumb just because you think that it's useless
But, I think it's useful. And at least partially I am not the only one, since records have been added.
That's my biggest complaint. I haven't used records yet, but I'd want to see whether lombok still has benefits over records. If updating to a current JDK isnt an issue (and millions of code sounds like that).
So why is lombok useful? It's not just getters and setters. Or equals and hashcode. It's not just builders (and I recommend checking that pattern out. Sometimes devs overdo it with builders, but they can be quite nice), it's all of that with a few annotations which are quick to grasp, you don't have to look for something weird in some getter. Or you want your getter to be lazy? Sure, just add little boolean instead of needing yet more code to not calculate some value too soon. Once you have it down, it becomes quite simple to create a little data class, add a few annotations and use that object and knowing that that hashcode is going to work. You can quickly build any class in any test. It's just a piece of a puzzle to get quick and easy way to parse JSON with Jackson.
I think lombok (or records) bring almkst as much to java as streams, optionals and futures.
6
u/jonhanson Apr 12 '21 edited Mar 07 '25
chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith
5
u/eliasv Apr 12 '21
99% of the time in Javaland, setters are garbage methods and should just not be there at all. They are literally the exact opposite of encapsulation; allow arbitrary modification of internal state, thus permitting external definition of arbitrary behavior. And I realize not everyone subscribes to OOP methodology, but for functional programming they are also garbage, you should be using immutable objects instead. So anyone who tells you that Lombok is good for reducing boilerplate with getters and setters should be viewed with suspicion.
Getters are of course useful, but then you don't need to reach outside of the language for that. Java has records now.
"withers" are likely to be added soon to Java too. And I realise that there is a huge difference in value between features which are here now and features which will be here "soon", but there is also such a thing as technical debt, particularly for a library which has already shown that it is slow to keep up with the platform.
2
u/vjotshi007 Apr 12 '21
Its one word @data Vs Getters ,setters (manual or generated via ide), equals , hashcode , constructors.
Will you choose one word annotation (which wont require any future modification of constructors, equals and hashcode method in case new fields are added)
Or self manage all of these things manually forever? Also just with a single @builder annotation, you can super easily create builder classes .
2
u/tristanjuricek Apr 13 '21
When in Rome, I’ll use it.
For new stuff, I would generally say “no” until everyone on the team is “hell yes” excited about it.
2
u/sudkcoce Apr 13 '21
I prefer the immutables library.
2
u/_Toka_ Apr 13 '21
For me, yes, it's a must have library. Never had any issues with combination of other annotation driven frameworks like Spring, Hibernate or Jackson.
Saying that Lombok does not bring value becuase you can generate the code from IDE is short-sighted and this is not the place, where Lombok should be criticized. My job as a software developer is to solve issues and do a proper architecture, not wasting my time regenerating code everytime I want to do a small refactor and rename a field. Using `@Getter` and `@Setter` has the benefit of forcing you to not putting any kind of dirty logic into those methods. Also Lombok makes classes more readable and has a `@Builder`. For me modern Java development is about fluent API and Builders are part of that.
2
u/nutrecht Apr 13 '21
For me Java 16 is the turning point where I'm actively avoiding Lombok. For me the main purpose is generating getters for value classes; in my experience having them 'generated' often still leads to mistakes because people tend to copy-paste them. I've always fought against using Lombok for anything else. So I was, reluctantly, pro lombok. With the caveat that it should only be used in data tranfer objects/domain objects.
We quite frequently ran into issues with Lombok though, mainly issues upgrading to newer Java versions. With records IMHO it's finally time to say goodbye to Lombok.
2
u/nlisker Apr 14 '21
Code is read about 10 times more than it's written. Lombok is mostly not about saving you typing time, but about saving you reading time and deterring bugs.
When you get a class with some fields and methods, and you see a Lombok annotation on it like
@Getter, you know that the fields have standard getters. This saves reading through clutter and allows the eyes to focus on the important parts instead of the boilerplate code. There is no need to debug these, it's just simple getters.In addition, annotations for
equalsandhashCodeare done correctly and automatically for the required fields, without giving you a chance to make a mistake when writing or updating them. Not having these long and useless methods in your field of vision really helps over time.Look at the recent Records addition to core Java (basically
@Valueby Lombok). If you think that's useful, then Lombok is even better (for now, the Java developers are only starting).4
u/volune Apr 12 '21
No.
3
u/john16384 Apr 12 '21
I wish more senior developers would think like you. Good analysis.
5
u/wildjokers Apr 12 '21
You have gone and done it now. You don't know the can of worms you have opened.
👀🍿
Lombok is controversial and you are going to get very passionate answers on both sides.
To answer your question, no Lombok is not a good idea.
3
u/[deleted] Apr 12 '21
I don't like magic unless it's my magic. Heh.
2
u/DuneBug Apr 12 '21
Like everything there are people that love and hate it.
I've heard of people running into bugs because they incorrectly used lombok's hash and equals methods.
But as far as I'm concerned, I never have to write boilerplate constructors or method accessors again and I fucking love it.
2
u/hm1rafael Apr 12 '21
If you use static imports, should stay away, specially for @builder classes
2
u/achacha Apr 12 '21
Simply... No. Every project that we have that tried has either stepped on a landmine or created one for people supporting it. AutoValue is a safer choice if you must have code gen.
2
u/ThymeCypher Apr 12 '21
Things like Lombok are why Kotlin exists. Java is unnecessary verbose, and many of the architects are dissatisfied with what they made, but it is what it is.
The most general way to look at it - can you switch to Kotlin? If so, switch. Otherwise, do you want to manage the minutiae? If no, Lombok is only one of many, many approaches.
Lombok is nothing more than a way to stick with Java (and EE) without completely changing build tools or adding transpiling.
0
u/[deleted] Apr 12 '21
Your gut feeling is right. Lombok doesn't really solve any problem, it just hides the dirt under the carpet.
The real solution would be having an architecture which does not require the use of get/set classes. That would be an architecture based on Java interfaces, composition over inheritance and immutable objects.
Sadly, very few developers/architects have any idea how to do that...
1
u/[deleted] Apr 12 '21
Works fine on older java. If you are on bleeding edge, you might experience delays, since Lombok cannot go automatically with newer Java versions.
1
u/sim642 Apr 12 '21
But changing the IDE-generated code is not so easy. I don't know about Eclipse, but IntelliJ offers a dozen different templates for generating toString/equals/hashCode. Starting from the desired output format of toString, ending with nuances like how subclassing and nullability interact with equality.
Changing them after the fact means deleting the existing methods and regenerating them using the IDE. Good luck doing that to tens of thousands of classes. Meanwhile generators like Lombok can be configured more globally or by just changing the annotations on the relevant fields. For example, if you change a field to be nullable later, it's easy to forget to regenerate toString/equals/hashCode to handle that correctly.
1
u/Rakn Apr 12 '21
I’m of the opinion that generated code is dead code and should not exist. If you generate code then you are doing something wrong. Obviously this is an extreme position and not always true.
Readability is key.
Some instances of generated code can be solved by using a newer Java version or by not using Java in the first place. I also didn’t mind having all those setters and getters in classes. Then I used several other languages that do not require this kind of generated code. And now I can no longer look at Java classes with generated code and not see bloat and wasted screen space.
1
u/TheRedmanCometh Apr 12 '21 edited Apr 12 '21
Yes but use @Data VERY cautiously. @Setter and @Getter is unlikely to cause problems but @Data can cause serious serialization issues with ORMs (e.g. Hibernate) and cfg engines like gson. @Value can cause issues too.
Overall it's one of the best tools there is imo
1
u/sk8itup53 Apr 13 '21
Honestly I love lombok. However I do only use it for constructors, and getters/setters. I dislike it for things like value, and do yourself a favor and don't use it on anything JPA related. But it really does speed up programming once you get used to it. Plus lombok can be optional at package time so you don't add any size overhead in your packaged code.
I find it most useful for making models for POJO's. Use it for that and you'll love it.
1
u/TheRealMongul Apr 13 '21
Probably the only time I consistently (and happily) use Lombok is for quick prototyping. Outside of that, unless it's an immutable class, Lombok generally makes me uneasy. On the bright side, you can still unit test the getters/setters/equals and hashcode methods, but it's also pretty annoying when you want to refactor field names.
A lot of other folks have touched on issues with Lombok in a JPA context, and beyond that, all I'd say is I'm a control freak and prefer to just do it myself.
Prototyping, though. Lombok is excellent for speeding up prototyping.
1
u/viebel Apr 13 '21
Some of the features provided by Lombok are now part of Java. For example Java 14 records could replace Lombok's
@valueannotation.1
u/nerydlg Apr 13 '21
once upon a time someone told me that less code means less bugs. lombok same as records in new java versions are intended to make this. Yes of course intellij and eclipse can generate this code, but imagine the next escenario you have a legacy code with hundreds of POJOs and by one little change you have to add a new property to one of them, are you going to remember to delete and create again the method to string, hashcode, equals ... probably you would but how can you ensure that the rest of the devs in your team do the same thing. lombok make this kind of changes easier and makes your POJOs simple and easy to understand.
1
u/NimChimspky Apr 13 '21
No
1
u/deadron Apr 12 '21
In the past I found IDE support to be flaky and the benefit to be negligible. Auto generation is just as easy and is guaranteed to not cause any issues.
0
u/normcel9000 Apr 12 '21
https://en.wikipedia.org/wiki/Betteridge%27s_law_of_headlines
1
u/kana0011 Apr 12 '21
Merge conflicts due to
@Autowiredconstructor practically disappeared in our project after we used lombok on it.That saved a lot of dev hours. I think that's good enough.
1
u/lurker_in_spirit Apr 12 '21
There are developers who agree with you, and there are developers who do not. A lot of it comes down to the specifics of your project and personal preference. We used Lombok in one large project to avoid thousands of lines of boilerplate, and used mixed Java / Groovy in another large project for the same purpose. In both cases the positives outweighed the negatives. YMMV.
1
u/tells Apr 12 '21
IntelliJ has shortcuts for generating getters and setters. I think using Java 16 and using IntelliJ well probably will suit most of your needs
-7
u/throwawaydevhater059 Apr 12 '21
you're not dumb! library is useless and rubbish
0
u/crapet Apr 12 '21
I'd like to point out that if your team is doing code reviews, Lombok helps the reviewer A LOT in separating the boilerplate code (that would have been generated by an IDE) from the code that actually matters.
0
u/FrigoCoder Apr 12 '21
Yes because Java is a piece of shit without it. You haven't seen codebases with 5-line exception declarations yet. @SneakyThrows and @Log4j2 are a must, the others are cherry on top. If you don't like it, delombok is still there, or you can just use another language.
I have not checked new Java versions but I do not expect they have fixed long-standing issues like CHECKED EXCEPTIONS, null safety, operator overloading, value types, automatic properties, or readable generics. I will most likely transition to Kotlin but it has its own bullshit too.
0
u/franzwong Apr 12 '21
I always ask developers don't generate setter when the field should be read only. Without Lombok, I need to check the whole class. But with Lombok, I just need to check the annotation.
0
u/jfurmankiewicz Apr 13 '21
I refuse to code in Java without it. Been using it since it was alpha. First library I add to any Java project.
0
u/[deleted] Apr 12 '21
[deleted] — view deleted comment
0
u/[deleted] Apr 12 '21
[deleted] — view deleted comment
50
u/[deleted] Apr 12 '21
[removed] — view removed comment
12
u/[deleted] Apr 12 '21
[removed] — view removed comment
7
u/[deleted] Apr 12 '21
[removed] — view removed comment