I have some big (more than 3 fields) objects that can and should be immutable. Every time I run into that case I tend to create constructor abominations with long parameter lists.
It doesn't feel right, it is hard to use, and readability suffers.
It is even worse if the fields are some sort of collection type like lists. A simple addSibling(S s)
would ease the object creation so much but renders the object mutable.
What do you guys use in such cases?
I'm on Scala and Java, but I think the problem is language agnostic as long as the language is object oriented.
Solutions I can think of:
The other object creates a new immutable instance of the class and the two objects are unaffiliated. For the same reason, an immutable does not need a copy constructor when copying an object.
Immutable objects can be useful in multi-threaded applications. Multiple threads can act on data represented by immutable objects without concern of the data being changed by other threads. Immutable objects are therefore considered more thread-safe than mutable objects.
The builder pattern hides the complexities of creating a class. In the case of an immutable class, it can be used to avoid constructors with too many parameters. Since the builder is not immutable, the values can be set through multiple calls.
Well, you want both an easier to read and immutable object once created?
I think a fluent interface CORRECTLY DONE would help you.
It would look like this (purely made up example):
final Foo immutable = FooFactory.create() .whereRangeConstraintsAre(100,300) .withColor(Color.BLUE) .withArea(234) .withInterspacing(12) .build();
I wrote "CORRECTLY DONE" in bold because most Java programmers get fluent interfaces wrong and pollute their object with the method necessary to build the object, which is of course completely wrong.
The trick is that only the build() method actually creates a Foo (hence you Foo can be immutable).
FooFactory.create(), whereXXX(..) and withXXX(..) all create "something else".
That something else may be a FooFactory, here's one way to do it....
You FooFactory would look like this:
// Notice the private FooFactory constructor private FooFactory() { } public static FooFactory create() { return new FooFactory(); } public FooFactory withColor( final Color col ) { this.color = color; return this; } public Foo build() { return new FooImpl( color, and, all, the, other, parameters, go, here ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With