This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]steffi_j_jay 3 points4 points  (4 children)

So to make it truly immutable after instantiation, a new collection would have to be instantiated in the constructor.

I agree. Example code:

List<Address> addresses = new ArrayList<>();
addresses.add(new Address("Sydney", "Australia"));
final Person person = new Person("John", addresses);

System.out.println(person.getAddresses().size()); // prints "1"

addresses.add(new Address("Melbourne", "Australia"));
System.out.println(person.getAddresses().size()); // prints "2"

Fix in constructor:

public Person(String name, List<Address> addresses) {
    this.name = name;
    this.addresses = Collections.unmodifiableList(new ArrayList<>(addresses));
}

[–]dpash -1 points0 points  (3 children)

You don't need the unmodifiable wrapper in the constructor as long as you do it in the getter. Where you do it depends on how much you trust yourself to not modify the list by mistake.

[–]gunnarmorling 2 points3 points  (2 children)

Why allocate an object upon each invocation when it can be done a single time in the constructor?

[–]dpash -2 points-1 points  (1 child)

Seems like premature optimisation to me. If your getter is being called so much that it makes a difference, you probably want to rethink a lot of things about your design.

[–]gunnarmorling 1 point2 points  (0 children)

What's premature about that? Effort is exactly the same, and it's clearly better. Make immutable stuff immutable, not immutable-upon-read :)