Building properly immutable objects in Java can be annoying, especially if they’ve got a bunch of properties – too many to put into a readable constructor.1
You can implement the Builder pattern, but a lot of the time that just feels like overkill. But you don’t want to put in a bunch of setter methods, because that’s just asking for trouble. So what do you do?
Get with()
it, of course. Replace all of your setXYZ()
with methods with a withXYZ()
method, that returns the object instance. Like so:
class Customer { private String name; public String getName() { return this.name; } public Customer withName(String name) { this.name = name; return this; } }
Pros:
- This is very quick and easy to write. Heck, you can generate your setters and easily convert them. (The one-line form used above is easy to replace with a regex, for example)
- Abuse is easy to detect – you just look for calls to
withXYZ()
that aren’t associated with a constructor. - Because you’re not using the standard Java Beans pattern, it doesn’t get picked up by any of the zillion tools that use the get/set pattern.
- The caller can chain calls, resulting in a very literate coding style (not unlike ObjectiveC, actually).
- It’s not a big deal to have a couple of parameters on a
withXYZ()
method, if the parameters are meant to go together – say, awithRocketAddress(double latitude, double longitude, double altitude)
Cons:
- Your object isn’t really immutable. People can still call the
withXYZ
method, and probably will if they don’t understand the convention. (They’ll probably also be cursing you and wondering why you don’t just call the methods setters). This isn’t that big a deal if you maintain code reviews – just invest in a cluebat2