While exercising your DDD skills, suppose you have object like this:
class Person {
Set<Address> addresses = new HashSet<Address>();
}
Is it more appropriate to allow normal/full access to the collection:
Set<Address> getAddresses() {
return addresses;
}
Which would allow the caller to add/remove addresses as they see fit, or, is it better to make callers go through the Person object in this case:
Set<Address> getAddresses() {
return Collections.unmodifiableSet(addresses);
}
void addAddress(Address address) {
addresses.add(address);
}
void removeAddress(Address address) {
addresses.remove(address);
}
The first case saves us from creating extra methods; the second case allows the Person object to be aware of changes to its addresses (in case it cared for one reason or another).
Is there a best-practice here?
I prefer the second approach, but I believe that the unmodifiable set buys you very little other than undesirable surprises in the client.
Had you wished to convey to the client that this collection is immutable, then you should have used a collection type which withheld mutability in its API (rather than it its implementation). That is, invoking a method which is declared to exist and catching a UnsupportedOperationException is like finding a unit on the woman with whom you have had your first date.
I love Josh Bloch, but I think he messed up on this one.