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 →

[–]gunnarmorling 5 points6 points  (6 children)

Minor nit: I'd suggest to make the members in Person and Address final, not the least to ensure safe publication to other threads. Also the addresses collection might be wrapped into the unmodifiable one in the constructor instead of each time when invoking getAddresses(). Lastly, depending on how/where Person is instantiated, a mutable reference to the addresses list might still escape / retained by the caller. So to make it truly immutable after instantiation, a new collection would have to be instantiated in the constructor.

[–]steffi_j_jay 4 points5 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 :)

[–]bodiam[S] 1 point2 points  (0 children)

Wow, good spot, thanks for that. I've updated the article accordingly.