Building big, immutable objects without using constructors having long parameter lists
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 );
}
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))
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.