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

前端 未结 9 819
星月不相逢
星月不相逢 2020-12-04 06:31

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

9条回答
  •  广开言路
    2020-12-04 06:58

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

提交回复
热议问题