Builder pattern for Java records

Brian Goetz brian.goetz at oracle.com
Sat May 22 20:35:15 UTC 2021


There is no end to patterns of code that could be generated by tools, and for each of them, one can imagine situations where they would be useful.  But in addition to the other reply about how builders are really only called for when there are a large number of _optional_ components, the premise of the question makes some incorrect assumptions about records.

Records are not a “macro generator”; to think of records in terms of “the compiler generates XYZ pattern of code”, while technically accurate, is missing the main point.  They are a semantic feature, that happens to dispense with some boilerplate.  

Records are best understood as _nominal tuples_; they are the language’s mechanism for representing product types.  Because Java is an OO language, we can mediate the construction process to reject invalid states or normalize state to its canonical form, and we derive the semantics for accessors, equals, hashCode, etc, from the semantics of tuples.  

If some project out there wants to have code generators for patterns that are sometimes useful for records, that’s great — but that’s not where the language should be focusing.  

> On May 21, 2021, at 11:37 AM, Alberto Otero Rodríguez <albest512 at hotmail.com> wrote:
> 
> Hi, I have found this project on GitHub which creates a Builder for Java records:
> https://github.com/Randgalt/record-builder
> [https://opengraph.githubassets.com/a4e3a7b3c7b16b51e0854011fe4b031577bcc09919058baef412b03613295d20/Randgalt/record-builder]<https://github.com/Randgalt/record-builder>
> GitHub - Randgalt/record-builder: Record builder generator for Java records<https://github.com/Randgalt/record-builder>
> The target package for generation is the same as the package that contains the "Include" annotation. Use packagePattern to change this (see Javadoc for details).. Usage Maven. Add the dependency that contains the @RecordBuilder annotation. < dependency > < groupId >io.soabase.record-builder</ groupId > < artifactId >record-builder-core</ artifactId > < version >set-version-here</ version ...
> github.com
> 
> And I was wondering if this could be made by default in all Java Records.
> 
> Technically a Builder is only used when creating the Object so I think is possible and, if Java creates it by default, would be less error prone than creating it manually.
> 
> Regards,
> 
> Alberto.



More information about the core-libs-dev mailing list