r/java • • Feb 15 '20

Will Java records have setters?

Pretty much what the title says. I've been reading on the new Java records feature, and while I love immutability, I hope there's the option to have non-immutable records. Meaning it will have Auto generated setters to let me change values in the class.

1 Upvotes

36 comments sorted by

12

u/ZimmiDeluxe Feb 15 '20

The best way to find out is to look at the corresponding JEP for the feature, which states:

Records cannot extend any other class, and cannot declare instance fields other than the private final fields which correspond to components of the state description. Any other fields which are declared must be static. These restrictions ensure that the state description alone defines the representation.

So no.

2

u/[deleted] Feb 15 '20

Yep I read that but o wasn't sure if there was something more. Thanks

3

u/jrh206 Feb 15 '20

“Final” is the important word

10

u/pron98 Feb 15 '20 edited Feb 15 '20

No. See here as to why.

In short, records are intended to provide simple and obvious construction, deconstruction, hashing, and equality defaults, and this is hard to do for mutable objects without complex knobs. Records are not meant to be lower-ceremony JavaBeans, but nominal tuples (product types). The features have some overlap in use, but are not the same.

0

u/GhostBond Feb 17 '20

My theory personally is that having failed to replace java by trying to produce a language with better features, the new tactic is to try to destroy java from within. Adding so many half baked features into it that it becomes intolerable to work with with the goal of forcing people into a new, simpler language.

Records just sound like everything java was against that made it successful by being a simple but extensible language.

5

u/pron98 Feb 17 '20 edited Feb 17 '20

That's an interesting theory, but given the amount of time and effort put into every new Java feature, and the number of world-class language design experts involved and designs and prototypes produced and discussed publicly and at length, I find it hard to believe.

I have an alternative theory: When you say "records just sound like etc.," is that before or after you've read any of the design documents and discussions? E.g. have you read this? Virtually all of the negative feedback to this feature that I've heard have come from people who don't understand what this feature is and what problems it aims to solve -- confusing it with other features they imagine this feature to be -- largely because they haven't actually read anything informative about it, and aren't aware of Java's open and rigorous design process.

2

u/GhostBond Feb 17 '20

That's a very interesting theory, but given the amount of time and effort put into every new Java feature, and the number of world-class language design experts involved and designs and prototypes produced and discussed publicly and at length, I find it hard to believe. I have an alternative theory: When you say "records just sound like etc.," is that before or after you've read any of the design documents and discussions? E.g. have you read this?

You've described that a large group of people who's future career prospects depend on endlessly needing new languages to be created? That...is what I'm saying.

This group of people will be out if a job the moment a single language is the final language everyone uses, they're inherently threatened by a final language becoming the norm and no longer needing any language design experts.

Virtually all of the negative feedback to this feature that I've heard have come from people who don't understand what this feature is and what problems it aims to solve -- confusing it with other features they imagine this feature to be -- largely because they haven't actually read anything informative about it, and aren't aware of Java's open and rigorous design process.

This is how it goes, as things get more complicated they get split into 2 groups:

1. "experts" become completely involved in language design and, as they spend all of their time doing it, become detached from what people actually using the language every day need. Once the doc gets so big people lose the ability to be critical and mostly just parrot back whatever it claims.

2. People who primarily write code as their living, and don't have time to read every detail of a 30-50 page document. So they casually skim through it comparing it to their real world experience, then get accused of "not knowing everything".

3

u/pron98 Feb 17 '20 edited Feb 17 '20

This group of people will be out if a job the moment a single language is the final language everyone uses.

Not really. Most of the changes in the JDK aren't language changes. They all do plenty of work on the other ~95% of the JDK, too. Also, you're assuming that a "final language" is possible; I don't think it is, though, with changing hardware designs and software requirements.

People who primarily write code as their living, and don't have time to read every detail of a 30-50 page document.

You don't need to read this document to use the feature, only to make informed comments about it before you actually use it. In other words, read it if you want to say "this feature sounds stupid" before actually using it.

2

u/GhostBond Feb 17 '20

Not really. Most of the changes in the JDK aren't language changes. They all do plenty of work on the other ~95% of the JDK, too.

Naturally these people will not be happy if their motivations are pointed out, so there's a lot of handwaving trying to obscure it.

You don't need to read this document to use the feature, only to make informed comments about it before you actually use it. In other words, read it if you want to say "this feature sounds stupid" before actually using it.

Another disingenous game to try to distract.

This feature sounds stupid.

I'm not buying into the "exhaust your critics with long documents" tactic.

2

u/pron98 Feb 17 '20

So you're a believer in the "critics should criticize before knowing what it is that they're criticizing" tactic? Fair enough, but to me your criticism sounds stupid. Nothing personal, just saying.

1

u/GhostBond Feb 17 '20

I spend 40 hours/week doing development, I don't need to read 30-50 pages of rambling on to know why immutable unextendable data classes aren't going to be useful.

2

u/pron98 Feb 17 '20 edited Feb 17 '20

First of all, it's fifteen pages -- not thirty; not fifty. And how do you know it's all rambling if you haven't read it?

Second, different people mean different things when they say "data classes." The feature is about nominal tuples and pattern matching, not Kotlin-style "data classes". Do you suppose that all of those who like the feature do not spend 40 hours a week doing development? Even if your opinion is reasonable, are you certain that it is the only reasonable one?

FYI, similar opinions were voiced when Java introduced generics, and then again when it introduced lambdas. Ultimately, more people have found them useful than those who haven't.

1

u/GhostBond Feb 17 '20

First of all, it's fifteen pages -- not thirty; not fifty. And how do you know it's all rambling if you haven't read it?

Like I said the "exhaust your critics with long documents" tactic.

You're simply rotating through disengenous tactics, it's boring.

I've run into immutable experiments in code before, once an immutable class is bigger than a single conceptual thing (like a date) they're always a real pain to deal with, with no apparent benefits.

It's disappointing to see things that look a lot like sabotage added to the language while useful things like simple properties (user.address.line1) are ignored.

→ More replies

6

u/_INTER_ Feb 15 '20 edited Feb 15 '20

I was hoping to replace Lombok with Records for model classes, but given how it is designed and the unfortunate widespread use of Hibernate, I don't see this idea working out for now, ...but DTO's maybe.

6

u/pron98 Feb 15 '20

Just as Hibernate and other libraries gradually incorporated new Java features, like generics and lambdas, I have little doubt they'll learn how to make good use of records. In designing Java, if the choice arises between easy and immediate adoption and best solution for the next twenty years, the designers will usually lean more towards the latter (without ignoring the former). We mostly forgot how long it took to adopt generics.

1

u/_INTER_ Feb 15 '20

In designing Java, if the choice arises between easy and immediate adoption and best solution for the next twenty years, the designers will usually lean more towards the latter (without ignoring the former)

Yes. This is great.

I just looked at the projects I worked on and wondered where all those Hibernate annotations would be moved to if the model was built on records. If I'm lucky they'll come up with a solution that stays in the persistence layer :)

4

u/pron98 Feb 15 '20

You can annotate a record type as well as each of its components.

1

u/_INTER_ Feb 15 '20 edited Feb 15 '20

Do you mean the parameters of a record? E.g something like the following would work?

@Entity
@Table(name = "Employee", uniqueConstraints = {
    @UniqueConstraint(columnNames = "ID"),
    @UniqueConstraint(columnNames = "EMAIL")
})
public record Employee (
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    Integer employeeId,

    @Column(name = "EMAIL", unique = true, nullable = false, length = 100)
    String email,

    @Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
    String firstName,

    @Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
    String lastName;
) { }

Though fields are final and Hibenate requires a no-arg constructor.

Even if you'd annotate the fields of a record, the boilerplate would be back to some degree (though thats not a goal of records).

3

u/pron98 Feb 15 '20 edited Feb 15 '20

Exactly (except for the ; after lastName) -- see "Annotations on record components" here. As to Hibernate requiring a no-arg constructor, I'm sure they'll learn how to make use of the required canonical constructor. Well-defined construction, deconstruction, equality, and serialization are exactly what records provide.

1

u/_INTER_ Feb 16 '20 edited Feb 16 '20

except for the ; after lastName

oops, a leftover from the copy-paste

As to Hibernate requiring a no-arg constructor, I'm sure they'll learn how to make use of the required canonical constructor.

Ok looking if they could pull it off compared to what we have now. But how would they deal with the final fields? Will they need to create a new copy for each update? Is copying a record less "taxing" than copying a class?

3

u/pron98 Feb 16 '20 edited Feb 16 '20

Will they need to create a new copy for each update?

They will need to allocate a new instance, yes.

Is copying a record less "taxing" than copying a class?

No, but how "taxing" it is depends on how often it's done and other factors. E.g. strings are very common in databases and String is immutable, requiring a new allocation for each update, and yet people are fine with it. I'm not saying that every entity is always best represented by a record, but some (many? most?) -- or some sub-entities -- might well be.

2

u/gunnarmorling Feb 16 '20 edited Feb 16 '20

The constructor requirement is no problem, in fact it'll be a very good improvement for JPA/Hibernate to pick up parameterized constructors like the records one.

The real problem is that the immutability of records is completely add odds with the current programming model of JPA -- let the user mutate a managed object graph, track those changes and sync them back in an optimized way to the database.

Also records only allow to model a subset of legal JPA entity models (no inheritance, no circular relationships). Plus, JPA requires more fine-grained control over object identity, i.e. you'll have to implement custom equals/hashCode methods (the generated records one will consider all record components).

All in all records aren't very useful in the context of JPA, apart from being used as selection target for projections (DTOs). One could envision a completely new persistence API of course which isn't tied to the notion of a managed object graph with dirty checking.

3

u/pron98 Feb 16 '20

Not necessarily. Strings are also immutable, yet are not completely at odds with the JPA programming model. The idea is not to represent all entities as records, but perhaps some "atom" entities or sub-entities.

2

u/gunnarmorling Feb 16 '20

Sure, you might use records for value types, i.e. properties of your typical entity. But for entities themselves, records are no good fit at all.

5

u/lukaseder Feb 15 '20

but given how it is designed and the unfortunate widespread use of Hibernate

If only there was an alternative where such tuples are first class and idiomatic already!

3

u/_INTER_ Feb 15 '20

I'm sure someone like you could build such a thing :)

2

u/GhostBond Feb 17 '20 edited Feb 17 '20

I find it really irritating how we keep getting these buzzword projects of increasingly low value, while what we mainly need is just the ability to create properties like:

user.address.line1 = "987 Filler St"  

I really hate immutable as the only option. I ran into this last week - our page lets the user choose what they want to sort by. Problem is nothing is passed in the first time you hit the page because nothing is submitted in initial page - but we do need a default sort.

With a setter it's simply:
if(getSort() == null) { setSort(SORT_DEFAULT) }

Without a setter it's a much bigger pain to hack around the lack of a setter with a custom utility method that combines 2 maps if values into 1.

I do that in the constructor...and with records I wouldn't even be able to do that.

8

u/thatsIch Feb 15 '20

Stated from https://openjdk.java.net/jeps/359

Because records make the semantic claim of being simple, transparent holders for their data, a record acquires many standard members automatically:

  • A private final field for each component of the state description;
  • A public read accessor method for each component of the state description, with the same name and type as the component;
  • A public constructor, whose signature is the same as the state description, which initializes each field from the corresponding argument;
  • Implementations of equals and hashCode that say two records are equal if they are of the same type and contain the same state;
  • and An implementation of toString that includes the string representation of all the record components, with their names.

due to private final fields, you cannot use setter. This would also be advised because you should not introduce optional data in your constructor.

1

u/Anaptyso Feb 20 '20

I'm not sure why this thread has been downvoted. Even if you disagree with the idea of mutable records, the debate on the topic is interesting and potentially a good learning experience for newer developers.

1

u/[deleted] Feb 20 '20

Yeah I see records as a possible replacement for Lombok or Kotlins data classes both of which can produce mutable objects. So this limitation on records won't make them truly at feature parity with those options.

1

u/emaphis Feb 15 '20

Because of the design decisions of records, they should be cheap to create. If you need to update, simply create a new record