views:

1165

answers:

10

Hi StackOverflow!

I have some big (more than 3 fields) Objects which 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, 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

Thanks for your input!

+3  A: 

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.

bmargulies
This is the Builder Pattern (option 2)
Simon Nickerson
Wouldn't that be a factory ('builder') object that emits his immutable objects?
bmargulies
@bmargulies: that distinction seems pretty semantic. How does the bean get made? How does that differ from a builder?
Carl
You don't want the package of Java Bean conventions for a builder (or for much else).
Tom Hawtin - tackline
+4  A: 

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.

ziggystar
The alleged downside - creating more instances than necessary - isn't really that much of a problem. Object allocation is very cheap, as is garbage collection of short-lived objects. When escape analysis is enabled by default, this kind of "intermediate objects" are likely to be stack allocated and cost literally nothing to create.
gustafc
@gustafc: Yep. Cliff Click once told the story of how they benchmarked Rich Hickey's Clojure Ant Colony simulation on one of their big boxes (864 cores, 768 GB RAM): 700 parallel threads running on 700 cores, each one at 100%, generating over 20 GB of ephemeral garbage *per second*. The GC didn't even break a sweat.
Jörg W Mittag
+3  A: 

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.

Carl
note: mileage for this answer may vary with problem, code-base, and developer skill.
Carl
+1  A: 

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.

Joren
+34  A: 

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 );
}
Webinator
@ all : please no complaint about the "Impl" postfix in "FooImpl": this class is hidden inside a factory and no one will ever see it besides the person writing the fluent interface. All the user cares about is that he gets a "Foo". I could have called "FooImpl" "FooPointlessNitpick" as well ;)
Webinator
Feeling pre-emptive? ;) You've been nitpicked in the past about this. :)
Greg D
Great answer, WizardOfOdds. I've seen this pattern successfully applied, and it really does meet the requirements expressed by the OP.
Tim Drisdelle
@Greg D: actually I don't think people nitpicked *me about it :) I think it's even the first I post a piece of code with "Impl" :) But I've sure *read* a lot of discussion/holy-wars on that subject here on SO ;)
Webinator
"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."What exactly do you mean by this? The example you posted is very close to the Builder pattern but using fluent naming. What is the common error?
pbh101
I believe the common error he's referring to is that people add the "withXXX" (etc) methods *to* the `Foo` object, rather than having a separate `FooFactory`.
Dean Harding
@pbh101: what codeka commented: in a lot of the blog/SO questions you see people doing what they think are "fluent interface" by adding the method related to object construction in the classes you want to construct. But, yup, basically a fluent interface is a specific form of the builder pattern (in the article here Joshua Bloch talks about that "special form": drdobbs.com/java/208403883?pgno=2 ). But the accepted term nowadays for such a construct is "fluent interface", not "builder pattern" (even if a fluent interface is done using a specific form of the builder pattern).
Webinator
@codeka: lets put it this way: every fluent interface in Java should be done using the Builder pattern but everytime the Builder pattern is used does not mean you're creating a "fluent interface".
Webinator
my comment @ http://stackoverflow.com/questions/114342/what-are-code-smells-what-is-the-best-way-to-correct-them/114360#114360
Behrooz
Your answer just triggered the "AHA!" I needed to understand why I've had issues when tinkering with fluent interfaces: it's the *factory* that's "fluent", not the object! Thanks. :-)
Rodney Gitzel
+5  A: 

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.

Little Bobby Tables
Option 1 is clever (but not *too* clever), so I like it.
Tim Drisdelle
I did this earlier, but in my opinion it is far away from being a good solution because the object is still mutable, only the mutating methods are "hidden". Maybe i am too picky about this subject...
Malax
A: 

I'd go with the fluent interface CORRECTLY DONE mentioned above. But a classic alternative (not pretty, but much more generic) is to initialize from a map.

public class GrandFather{

    private final Foo foo;

    public static final String PARAM_FOO = "foo";
    public GrandFather(Map<String, Object> parameters){
        Assert.notNull(parameters);
        this.foo=(Foo)parameters.get(PARAM_FOO);
        Assert.notNull(this.foo);
    }

}

public class Father{

        private final Bar bar;

        public static final String PARAM_BAR = "bar";
        public Father(Map<String, Object> parameters){
                super(parameters);
                this.bar=(Bar)parameters.get(PARAM_BAR);
                Assert.notNull(this.bar);
        }

}

public class Child{

        private final Buzz buzz;

        public static final String PARAM_BUZZ = "buzz";
        public Child(Map<String, Object> parameters){
                super(parameters);
                this.buzz=(Buzz)parameters.get(PARAM_BUZZ);
                Assert.notNull(this.buzz);
        }

}    

As you can see, this works fine even for class hierarchies. However, some discipline is required.

  • First of all, only use constants as map keys. Otherwise a simple refactoring breaks everything.
  • Second, use parameter validation. I always use either the spring Assert class (because I don't want runtime dependencies to JUnit) or write my own custom validation class if spring is not available.
  • Third, be careful to make your parameters unique. Can't help you with that. Actually I can: Make the map key an enum instead of a string.

Sean

seanizer
No offense, but... WTF? I never ever will do such a thing in my life. :-) (At least in a statically typed language like Java or Scala) But as said, no offense, thanks for your answer!
Malax
As I said, I would prefer the fluent interface in my own code, but when you use an existing framework, you will sometimes find the above pattern. For example in wicket (web framework), page objects have a constructor with a pageMap which is just a map with some sugar added. Sean
seanizer
+29  A: 

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))
Martin Odersky
+1 for inventing the Scala language. Yeah, it's an abuse of the reputation system but... aww... I love Scala so much i had to do it. :)
Malax
Oh, man... I have just answered something almost identical! Well, I'm in good company. :-) I wonder that I didn't see your answer before, though... <shrug>
Daniel
+12  A: 

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.

Daniel
+1  A: 

It helps to remember there are 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.

Juliet
Downvotes? Anyone want to leave a comment on why this isn't a good solution?
Juliet
+1. Maybe someone downvoted this because you are hinting at the use of `clone()` to derive new instances.
finnw
Or maybe it was because it can compromise thread safety in Java: http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.5
finnw