Draft JLS spec for records
brian.goetz at oracle.com
Thu Sep 5 13:49:25 UTC 2019
> can someone explain me why we need the constructor to be public ?
The essence of records is: “the author gives up the right to decouple the public API from the representation.” That means that the construction, deconstruction, access, equality, hashing, and textualization protocols are derived from the representation.
There needs to be a deterministic, mechanically-derivable-from-the-state-vector way to construct a record instance. Serialization, for example, would use this for reconstructing the object; frameworks like O/R mappers would do the same. Allowing the user to withdraw the constructor from the API would undermine this.
Now, you might say “but I want my API to have factories, not constructors, because constructors are old and smelly”*. And if factories were a language concept, I would agree 100%, and would prefer to have a private ctor with public factory. But factories are not a language concept, and it would be pretty questionable for the language to bless a name like “make” or “of” as the name for the automatically generated factory method.
So while “public constructor” is not ideal, it’s less bad than the alternatives that have presented themselves so far.
*Note that one of the biggest benefits of factories, that you might return a subclass, isn’t in play with records anyway, since records are final. The main thing a factory could do here is return a cached instance. Which is not nothing, but not quite as useful as factories are in the general case.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the amber-spec-experts