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

前端 未结 9 803
星月不相逢
星月不相逢 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:54

    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.

提交回复
热议问题