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

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.