Building big, immutable objects without using constructors having long parameter lists

JavaOopScalaImmutability

Java Problem Overview


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:

  1. "Constructor abominations with long parameter lists"
  2. The Builder Pattern

Java Solutions


Solution 1 - Java

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 );
}

Solution 2 - Java

In Scala 2.8, you could use named and default parameters as well as the copy method on a case class. Here's some example code:

case class Person(name: String, age: Int, children: List[Person] = List()) {
  def addChild(p: Person) = copy(children = p :: this.children)
}

val parent = Person(name = "Bob", age = 55)
  .addChild(Person("Lisa", 23))
  .addChild(Person("Peter", 16))

Solution 3 - Java

Well, consider this on Scala 2.8:

case class Person(name: String, 
                  married: Boolean = false, 
                  espouse: Option[String] = None, 
                  children: Set[String] = Set.empty) {
  def marriedTo(whom: String) = this.copy(married = true, espouse = Some(whom))
  def addChild(whom: String) = this.copy(children = children + whom)
}

scala> Person("Joseph").marriedTo("Mary").addChild("Jesus")
res1: Person = Person(Joseph,true,Some(Mary),Set(Jesus))

This does have its share of problems, of course. For instance, try making espouse and Option[Person], and then getting two persons married to each other. I can't think of a way to solve that without resorting to either a private var and/or a private constructor plus a factory.

Solution 4 - Java

Here are a couple of more options:

Option 1

Make the implementation itself mutable, but separate the interfaces that it exposes to mutable and immutable. This is taken from the Swing library design.

public interface Foo {
  X getX();
  Y getY();
}

public interface MutableFoo extends Foo {
  void setX(X x);
  void setY(Y y);
}

public class FooImpl implements MutableFoo {...}

public SomeClassThatUsesFoo {
  public Foo makeFoo(...) {
    MutableFoo ret = new MutableFoo...
    ret.setX(...);
    ret.setY(...);
    return ret; // As Foo, not MutableFoo
  }
}
Option 2

If your application contains a large but pre-defined set of immutable objects (e.g., configuration objects), you might consider using the Spring framework.

Solution 5 - Java

It helps to remember there are http://blogs.msdn.com/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx">different kinds of immutability. For your case, I think "popsicle" immutability will work really well:

> Popsicle immutability: is what I > whimsically call a slight weakening of > write-once immutability. One could > imagine an object or a field which > remained mutable for a little while > during its initialization, and then > got “frozen” forever. This kind of > immutability is particularly useful > for immutable objects which circularly > reference each other, or immutable > objects which have been serialized to > disk and upon deserialization need to > be “fluid” until the entire > deserialization process is done, at > which point all the objects may be > frozen.

So you initialize your object, then set a "freeze" flag of some sort indicating that its no longer writable. Preferably, you'd hide the mutation behind a function so the function is still pure to clients consuming your API.

Solution 6 - Java

Consider four possibilities:

new Immutable(one, fish, two, fish, red, fish, blue, fish); /*1 */

params = new ImmutableParameters(); /*2 */
params.setType("fowl");
new Immutable(params);

factory = new ImmutableFactory(); /*3 */
factory.setType("fish");
factory.getInstance();

Immutable boringImmutable = new Immutable(); /* 4 */
Immutable lessBoring = boringImmutable.setType("vegetable");

To me, each of 2, 3, and 4 is adapted to a difference situation. The first one is hard to love, for the reasons cited by the OP, and is generally a symptom of a design that has suffered some creep and needs some refactoring.

What I'm listing as (2) is good when there is no state behind the 'factory', whereas (3) is the design of choice when there is state. I find myself using (2) rather than (3) when I don't want to worry about threads and synchronization, and I don't need to worry about amortizing some expensive setup over the production of many objects. (3), on the other hand, is called forth when real work goes into the construction of the factory (setting up from an SPI, reading configuration files, etc).

Finally, someone else's answer mentioned option (4), where you have lots of little immutable objects and the preferable pattern is to get news ones from old ones.

Note that I'm not a member of the 'pattern fan club' -- sure, some things are worth emulating, but it seems to me that they take on an unhelpful life of their own once people give them names and funny hats.

Solution 7 - Java

You could also make the immutable objects expose methods that look like mutators (like addSibling) but let them return a new instance. That's what the immutable Scala collections do.

The downside is that you might create more instances than necessary. It's also only applicable when there exist intermediate valid configurations (like some node without siblings which is ok in most cases) unless you don't want to deal with partially built objects.

For example a graph edge which has no destination yet isn't a valid graph edge.

Solution 8 - Java

Another potential option is to refactor to have fewer configurable fields. If groups of fields only work (mostly) with each other, gather them up into their own small immutable object. That "small" object's constructors/builders should be more manageable, as will the constructor/builder for this "big" object.

Solution 9 - Java

I use C#, and these are my approaches. Consider:

class Foo
{
    // private fields only to be written inside a constructor
    private readonly int i;
    private readonly string s;
    private readonly Bar b;

    // public getter properties
    public int I { get { return i; } }
    // etc.
}

Option 1. Constructor with optional parameters

public Foo(int i = 0, string s = "bla", Bar b = null)
{
    this.i = i;
    this.s = s;
    this.b = b;
}

Used as e.g. new Foo(5, b: new Bar(whatever)). Not for Java or C# versions before 4.0. but still worth showing, as it's an example how not all solutions are language agnostic.

Option 2. Constructor taking a single parameter object

public Foo(FooParameters parameters)
{
    this.i = parameters.I;
    // etc.
}

class FooParameters
{
    // public properties with automatically generated private backing fields
    public int I { get; set; }
    public string S { get; set; }
    public Bar B { get; set; }
    
    // All properties are public, so we don't need a full constructor.
    // For convenience, you could include some commonly used initialization
    // patterns as additional constructors.
    public FooParameters() { }
}

Usage example:

FooParameters fp = new FooParameters();
fp.I = 5;
fp.S = "bla";
fp.B = new Bar();
Foo f = new Foo(fp);`

C# from 3.0 on makes this more elegant with object initializer syntax (semantically equivalent to the previous example):

FooParameters fp = new FooParameters { I = 5, S = "bla", B = new Bar() };
Foo f = new Foo(fp);

Option 3:
Redesign your class not to need such a huge number of parameters. You could split its repsonsibilities into multiple classes. Or pass parameters not to the constructor but only to specific methods, on demand. Not always viable, but when it is, it's worth doing.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMalaxView Question on Stackoverflow
Solution 1 - JavaSyntaxT3rr0rView Answer on Stackoverflow
Solution 2 - JavaMartin OderskyView Answer on Stackoverflow
Solution 3 - JavaDaniel C. SobralView Answer on Stackoverflow
Solution 4 - JavaLittle Bobby TablesView Answer on Stackoverflow
Solution 5 - JavaJulietView Answer on Stackoverflow
Solution 6 - JavabmarguliesView Answer on Stackoverflow
Solution 7 - JavaziggystarView Answer on Stackoverflow
Solution 8 - JavaCarlView Answer on Stackoverflow
Solution 9 - JavaJorenView Answer on Stackoverflow