With an immutable object, where is it proper to wrap a contained collection as unmodifiable? I see 3 options:
In the immutable object's factory:
public class ImmutableFactory { public Immutable build(){ List<Integer> values = new ArrayList<Integer>(); values.add(1); values.add(2); values.add(3); return new Immutable(Collections.unmodifiableList(values), "hello"); } }
In the immutable's contructor
public class Immutable { private final List<Integer> values; private final String hello; public Immutable(List<Integer> values, String hello) { this.values = Collections.unmodifiableList(values); this.hello = hello; } public List<Integer> getValues() { return values; } public String getHello() { return hello; } }
In the immutable's accessor (if applicable).
public class Immutable { private final List<Integer> values; private final String hello; public Immutable(List<Integer> values, String hello) { this.values = values; this.hello = hello; } public List<Integer> getValues() { return Collections.unmodifiableList(values); } public String getHello() { return hello; } }
Are there any other options and which one is proper?
See Question&Answers more detail:os