TTar
TTar

Reputation: 925

Wrapping access to collections in DDD?

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?

Upvotes: 4

Views: 299

Answers (5)

sweetjonnie
sweetjonnie

Reputation: 98

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.

Upvotes: 3

casablanca
casablanca

Reputation: 70721

Either way is okay, but for the sake of clarity, I would name the methods differently based on whether the returned set is mutable or not:

Set<Address> getAddresses() {
    return Collections.unmodifiableSet(addresses);
}

Set<Address> addresses() {
    return addresses;
}

Upvotes: 0

Matt
Matt

Reputation: 11805

This all depends on your requirements. If there's good reason to keep the underlying collection away from the clients of the class, then you do it. Otherwise, there's usually no downside to providing set/get methods.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 994081

I would say that in general, the second approach is more robust. Using an unmodifiable set as the return prevents outsiders from being able to change the internal state of the Person class. If the Person class logically owns their addresses, then others shouldn't be able to make changes without going through Person class methods.

Upvotes: 1

Muhammad Gelbana
Muhammad Gelbana

Reputation: 4010

I can't see a good or a bad thing about the 2 approaches. It's all about what functionality your class is willing to offer.

Upvotes: 0

Related Questions