DEV Community

Discussion on: Make an Immutable Object - in Java

Collapse
 
frothandjava profile image
Scot McSweeney-Roberts

If you make the Builder a static inner class then you can give the class you're building a private constructor that takes an object of the Builder class. So you end up with

final Dog dog = ImmutableDog.builder().name("fido").weight(20).build();

Doing it this way enforces using the builder and I've found it helps with maintenance

You might have noticed that I don't bother with get/set prefixes on Builders - they're not Beans and I'm probably never going to read a value that I'm putting into the builder.

Collapse
 
monknomo profile image
Gunnar Gissel

That's a nice way of doing it, and I prefer creating the immutable class from the builder.

I've found getters useful on builders for doing the final validation before creating the real immutable object - how do you usually handle validation?

Collapse
 
frothandjava profile image
Scot McSweeney-Roberts

A mix of in the not-a-setter method and the build method before calling the constructor (and maybe occasionally in the constructor, but not by preference). Depends on exactly why it's not valid.