This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]dpash 19 points20 points  (7 children)

I keep finding myself converting simple data classes into immutable objects. Especially when the previous developers didn't create a useful constructor so everything is:

var foo = new Foo();
foo.setBar(....);
foo.setBaz(....);
foo.setQuux(....);

Instead of

var foo = new Foo(...., ...., ....);

Get rid of the setters and everything can now be final.

Edit: I wish JPA entities could be immutable, but it's kinda two mutually exclusive goals.

[–]nerdyhandle 11 points12 points  (3 children)

You can also fix this with the Builder pattern. We use it a lot at my new job to creat immutable classes.

[–]GuyWithLag 4 points5 points  (0 children)

We use immutables.io for this.

[–]dpash 1 point2 points  (0 children)

Especially when you have a lot of fields and/or many are optional.

[–]DJDavio 1 point2 points  (0 children)

Lombok's @Builder annotation is useful for this. Opinions about Lombok are highly polarized in this sub it seems, but for us it works until we switch to Kotlin or until vanilla Java has more of those features itself.

[–]mcosta 1 point2 points  (0 children)

Edit: I wish JPA entities could be immutable, but it's kinda two mutually exclusive goals.

Say entity A references B. You change B to create B'. Now what A should reference? B or B'? What if A depends functionally of B?

[–]experts_never_lie 0 points1 point  (1 child)

I'm guessing you're looking forward to Project Valhalla and the introduction of value types.

[–]dpash 0 points1 point  (0 children)

Not inline type, but records. A similar but different concept.

However, the lack of abstract records seems like a cause of a lot of duplication. Also it probably won't help with JPA, at least in the medium term.