r/java • • Dec 21 '25

After writing millions of lines of code, I created another record builder.

Background

After writing millions of lines of Java code, here are my findings:

  1. Record can replace part of Lombok's capabilities, but before Java has named parameter constructors with default values, the Builder pattern remains the best solution for object construction (although it still has boilerplate code).
  2. Protobuf made many correct API design decisions:

    • One single way to build objects (builder)
    • Not null by default (does not accept or return null)
    • Builder class has getter/has/clear methods

Based on this, I created another record builder inspired by Protobuf, which provides no custom capabilities, does not accept null (unless explicitly declared as Nullable), and simply offers one way to do one thing well.

// Source code

import recordbuilder.RecordBuilder;
import org.jspecify.annotations.Nullable;


public record User(
    String name,
    Integer age,
    @Nullable String email
) {}

// Generated code

public final class UserBuilder {
    private String _name;
    private Integer _age;
    private @Nullable String _email;

    private UserBuilder() {}

    // Factory methods
    public static UserBuilder builder() { ... }
    public static UserBuilder builder(User prototype) { ... }

    // Merge method
    public UserBuilder merge(User other) { ... }

    // Setter methods (fluent API)
    public UserBuilder setName(String name) { ... }
    public UserBuilder setAge(Integer age) { ... }
    public UserBuilder setEmail(@Nullable String email) { ... }

    // Has methods (check if field was set)
    public boolean hasName() { ... }
    public boolean hasAge() { ... }
    public boolean hasEmail() { ... }

    // Getter methods
    public String getName() { ... }
    public Integer getAge() { ... }
    public @Nullable String getEmail() { ... }

    // Clear methods
    public UserBuilder clearName() { ... }
    public UserBuilder clearAge() { ... }
    public UserBuilder clearEmail() { ... }

    // Build method
    public User build() { ... }

    // toString
    u/Override
    public String toString() { ... }
}

GitHub: https://github.com/DanielLiu1123/recordbuilder

Feedback welcome!

83 Upvotes

53 comments sorted by

View all comments

Show parent comment

23

u/edzorg Dec 21 '25

Why would you remove Lombok? In favour of what?

Aren't you swapping a bunch of annotations for 10x lines of code of #equals #hashcode getters etc?

9

u/beefquoner Dec 21 '25

records essentially remove the need for all the things you listed?

58

u/repeating_bears Dec 21 '25

No they don't. They remove the need for them in shallowly immutable data carriers.

If your class needs to mutable or you don't want to expose every single field, you can't use a record.

4

u/OwnBreakfast1114 Dec 23 '25 edited Dec 29 '25

No they don't. They remove the need for them in shallowly immutable data carriers. If your class needs to mutable or you don't want to expose every single field, you can't use a record.

All of these talking points are so codebase/style specific.

For us, we've basically been able to strip out almost all our @Value annotations which are the majority of our classes.

We have very few mutable classes (no spring component really needs to be mutable, though they're better done as @Required/AllArgConstructor over records since there's no accessors/getters necessary), and db objects are handled by methods that return a "new" version of the object. We force all arg constructors as they turn adding/removing fields into a compile time error instead of a run time error and we add fields to our domain objects all the time.

We haven't really "removed" lombok, but it's usage has gone down tremendously. @Log, @Required/AllArgs. We banned builders for the above mentioned reason anyway, so that was never a problem.

6

u/nonFungibleHuman Dec 21 '25

But in my project we also use @RequiredParamsConstructor (or the like)

8

u/antihemispherist Dec 21 '25

Then you'll have difficulty in debugging your constructor, and more importantly, you may tend to skip having validations in your contructors.

Constructors are not boilerplate

15

u/rzwitserloot Dec 22 '25

They usually are. If they are not, then.. don't lombok them.

And, even better, if they are today but when updating your code you realize your constructor is no longer boilerplate, you simply remove the lombok annotation and write it out. Your API is 100% backwards compatible in all sense of the word. Callers can't even tell you changed it.

Note that records themselves 'treat it as boilerplate', in the sense that if you don't write a constructor for a record, that's no problem; you get the default one which sets all 'fields' and does no validation whatsoever.

3

u/antihemispherist Dec 22 '25

Yes and no. Records are mainly used to carry data. We do not usually inject a Connection instance to a record, but we do this to a service. There, it may be useful to debug the constructor, see what actually has been injected, with which parameters. Besides, validating one input field on record constructor requires adding single line to its compact contsructor. On a regular class, you de-lombok the constructor, which looks bloated, but you have a more robust code. this bloated looking code leads to disputes in reviews, seems like a step back to the inexperienced, reduces team productivity. Therefore, it is better to avoid lombok in the first place, if we were to prioritize long term maintainability and robustness over aesthetics.

3

u/rzwitserloot Dec 23 '25

Purely anecdotal of course, and I may well be biased, but I replace lombok code with OpenJDK stuff all the time (i.e. I don't think I am biased):

I rarely use records. By which I mean: I have about 1 record for every 5 record-esque classes, give or take. A 20% 'hit rate'. With 'record-esque' I mean: The class is primarily intended as a data vehicle.

4 out of 5 have something that would make using a record impossible or at least annoying:

  • They have type hierarchy (records can't extend anything).
  • There is an actual, or plausible-in-the-near-future 1 need to cache values. The day-job code has a lot of complicated data wrangling so this is biased to my job a little bit, but bare bones CRUD-like coding is lost to AI anyway.
  • API control is warranted: The exposure of its properties are not all at the same level. For example, I want the construction of them and certain properties to be restricted to the package, but the record's type itself, and other properties, can be public. If a record is public, then its constructor must also be (it's a compiler error even if you just redefine it solely for the purpose of whacking an access mod on it). I'm not going to ugly up the general API in order to 'save typing', and I don't think a thing being a record is inherently a bonus, i.e. there is no point trying to weigh the 'upside' of "well, its a record!" against the downside of "... it has a constructor that is exposed to code that has absolutely no business calling it".

That third point is, in the end, a style consideration. But one I'm pretty set on, and I think most of the community agrees. Essentially ignoring the concept of access modifiers is bad / 'access' goes a little further than 'forbid' - access modifiers also constraint API: If it's hard to imagine how code outside of the package is meant to even use a certain method, then do not expose it. It makes reasoning about your code simpler, and more to the point perhaps, it makes reasoning about your type from the viewpoint of other packages much simpler: That method you don't expose is one you don't even have to know about, after all.

But about half of those '4 out of 5' need a bunch of boilerplate. Lombok therefore remains 100% required for sane java coding. And this will not change anytime soon (SOURCE: Recent OpenJDK panel session with all the movers and shakers (including Goetz and Reinhold), where the question was asked: "So, boilerplate removal" and the answer was a clear: "No!" - they spent more words, though).


[1] I fucking hate pithy programming 'principles' being applied to everything with no room for experience and artistry. YAGNI? If my experience and knowledge of the domain is telling me that I likely will, and soon, then I won't program ourselves into a corner whilst raising the banner of YAGNI, of course.

2

u/antihemispherist Dec 25 '25

You can (and should) separate the classes for interim state, where the date is being collected and the consistent, stable state, where the data represents a stable state on the business domain. Records should represent these stable states. They should have a clear noun name and meaning, matching the business concept / state. They should have validation in their constructor, and being immutable is what you actually need and have with records.

A builder for this record should hold the interim state, which gets build during processing. For almost all the cases, all you need is a builder, not a mutable class. That'll result in more robust design

3

u/rzwitserloot Dec 26 '25

I don't think you understood anything I wrote, then.

"Records should present these stable states"

How does that 'answer' / counterpoint my argument of "Good API design sometimes indicates that not all properties should be equally visible to all users of a type", for example?

"the build-up state and the final state should be different types"

How does that obviate "sometimes good API design indicates your final state carriers should have a type hierarchy of some sort"?

"you should pretty much always separate your build-up state carrier from your final state carrier"

That's a terrible plan if your aim is to reduce boilerplate!

If your goal is to be fairly ruthless about separating state carrier types into 2 'worlds' (build-up phase vs use phase), then lombok or tools like it have a crucial role.

I really don't think you can get away with leaning on the developer to put in the effort. Making 2 types that overlap significantly and semantically are separated by a nuanced notion (such as 'build up phase' vs 'use phase'), where the effort required to make the second type is more involved that a small one-liner or modifier, is bad advice. Because humans are gonna human, and won't do it. Even if you call that pilot error and demand that they must, then you're now foisting a lot of boilerplate typing onto 'you aren't a good programmer unless you do this'.

What's actually going to happen is that folks will write one type if the current requirements say you can get away with that, and then when future change requests/milestone advancement changes things and now having 2 separate types is clearly design-wise superior, then the type will not be split because doing that is a lot of effort - you can't do that with a refactor script! Every user of a type needs to be 'sorted' into one of 2 'kinds': The "build up phase" kinda user, or the "use phase" kinda user. There's no way to tell without a bunch of intelligence. And possibly some code already violated some rules (they straddle the divide and are a bot of both; if the types were split from the get go that probably wouldn't have happened).

Hence, to me at any rate, either [A] you split them from day 1, or [B] this boils down to nice sounding academic drivel: A neat goal that will not survive contact with reality.

Gets right back to 'if this is good design you need tools to make it easy', and bare bones OpenJDK+records do not provide it.

1

u/nlisker Feb 10 '26

And this will not change anytime soon (SOURCE: Recent OpenJDK panel session with all the movers and shakers (including Goetz and Reinhold), where the question was asked: "So, boilerplate removal" and the answer was a clear: "No!" - they spent more words, though).

We recently got a look into carrier classes, which allow things like caching and I think more flexible visibility too.

2

u/rzwitserloot Dec 23 '25

Therefore, it is better to avoid lombok in the first place, if we were to prioritize long term maintainability and robustness over aesthetics.

"Lombok is good but in this instance could use a feature it currently does not have, so better not use it all!".

You can easily craft an analogous argument where your point of view concludes that you must program everything in direct machine code because programming languages every so often have downsides.

That's not to say your argument is completely without merit, but that it is oversimplified. It's not a black and white situation. "A tool does not cater to 100% of the requirements" does not automatically imply "...therefore you must not use it".

Weigh the cost/benefit analysis. Biased of course, but I'd be extremely surprised if a reasonable analysis for your codebase concludes 'best not use lombok at all'.

A way to add validation for certain fields is on our radar. It's just hard to come up with a way to give it with nice syntax. We have taken the stand that we don't mess with the syntax of java. In other words, your code has to be syntactically valid before lombok 'gets to run'. And therein lies the rub. We can conjure up non-existant methods, inject code, give annotations meanings beyond 'visible to APs and runtime stuff'. But we can't invent syntax.

2

u/antihemispherist Dec 25 '25

Unfortunately, Lombok is very prone to misuse / overuse. That's my observation over the decades.

I've seen @SneakyThrows being used on almost every checked exceptions (almost no one reads the document and many believes that shorter looking code is better), I see @Data being preferred over records or @Value. I see validations on constructors being skipped, in favor of concise syntax provided by @RequiredArgsConstructor etc. Fixings these may get rejected or leads to disputes, cause it doesn't look as nice, or having the flexibility of modifying fields seems like a good idea.

Is it the developers fault? Maybe. Depends on the team. In practice, I have experienced that not using Lombok helps with guiding to better design decisions.

Besides, sometimes it leads to maintenance issues when upgrading Java or debugging remotely etc. Not sure if using it is an improvement over generating boilerplate using IDE and having a good encapsulation. It does however give a good sense of tidiness, because our intuition is mostly guided by our vision. I wrote about it some time ago in here: https://berksoftware.com/24/10/Using-Lombok-wisely

Since you're a maintainer of it, here is an improvement idea: Distribute experimental stuff in a separate dependency. May help with reducing misuse.

3

u/DelayLucky Dec 26 '25

Completely agree!

Unless the custom utility offers compelling benefit, having a different syntax than the standard to achieve the same result is not good.

A while back in another thread, I was shown the usage of @Cleanupto unlock a renentrant lock.

Besides the magically inserted code, the main perceived benefit compared to try-with-resources is the saving of indentation, which I disagreed.

And I can't convince myself that writing "unlock" in a string literal is better than explicit, visible code: lock.unlock()

Though, I also sympathize with the argument that records are not useful when you want equals/hashCode but still want to hide the data from the outside world.

32

u/Cell-i-Zenit Dec 21 '25

Then you'll have difficulty in debugging your constructor, and more importantly, you may tend to skip having validations in your contructors.

The whole point of this annotation is that the constructor is essentially passthrough and there is no need to debug or add validation here.

Constructors are not boilerplate

They are in the spring world most of the time

11

u/Ignisami Dec 21 '25 edited Dec 21 '25

Must be nice to work in an environment where you can just use records. Unfortunately, a lot of people work with classes that codify the behaviour of the objects they represent as much as the data they can carry.
Records are great at carrying data (and I personally do use them liberally for (de)serialization), not so much behaviour.

edit just for clarity: so even with Records you still end up with plenty of places where a builder can make sense. The couple of projects at work where we can use Records (because the rest is only just now migrating away from Java 8) still bring in Lombok for basic @Builder/@Data annotations on behaviour-encoding and mutable classes alongside the use of records for API requests/reponses.

5

u/trodiix Dec 21 '25

But records are immutable so you still need classes and then you have to use getters, setters, equals, hashcode and toString

5

u/Ignisami Dec 21 '25

And you can use Lombok for that, as I said in my edit. I find I quite like Lombok's defaults, and just sticking to the built-in annotations doesn't cause many problems (especially in an environment that always waits a version or two/three before upgrading if there aren't security concerns, like mine).

Records are very nice indeed, but can't replace Lombok in its entirety (unless you're willing to write boilerplate, I guess). If my post gave the impression that I was arguing otherwise, I apologize.

1

u/edzorg Jan 03 '26

"Just use records" and "You dont need it anyway" are representative of the typical arguments for avoiding/removing Lombok. Thanks!

-2

u/foreveratom Dec 22 '25

How often do you really need to implement equals and hashcode? And what IDE are you using that doesn't generate getters and setters with a shortcut?

14

u/rzwitserloot Dec 22 '25

The problem with letting your IDE generate them, is that you have to maintain that and look at it. Code isn't carved out of marble. It tends to be modified.

If you have a boatload of IDE-generated boilerplate, and there's one getter in there that does something a little wonky, that's hard to spot amongst all the noise. Not so with lombok. Or with most other generators.

If you have a boatload of IDE generated boilerplate and you add a field, will you remember to wipe out the equals and hashCode and ask your IDE to generate them anew? You sure those methods didn't contain modifications you just accidentally deleted? If you forget, it won't really be obvious. (no compiler errors, for example). Likely that will be a bug that goes undiscovered for quite a while and can cause hours of damage, if not more.

Excuse the directness, but that sentiment strikes me as someone who doesn't maintain any projects larger than ~1 personyear of effort. Perhaps you just code differently, but I find it hard to imagine how you end up with heaps of code that you pretty much never touch again.

→ More replies (3)