Krzysztof
Krzysztof

Reputation: 2082

DDD how to properly return collections of entities?

I have:

@DomainAggregate
@Entity
class Meeting {

... more fields here

private Set<AppUser> guests;

public Set<AppUser> getGuests() {
    return Collections.unmodifiableSet(guests);
}
}

and AppUser is entity (not value object). I am confused what is correct way of returning collection. Is my way correct according to DDD? (collection cant be modified but, elements of it can) or maybe I should create dto class for my AppUser objects? (this will allow me ensure that any data from inside aggregate cant be accessed from outside of it but will force few operations more like: create dto, copy data, etc.)

Upvotes: 0

Views: 778

Answers (1)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57289

Is my way correct according to DDD?

According to Evans Chapter 6, it is acceptable. He wrote (back in 2003)

Nothing outside the AGGREGATE boundary can hold a reference to anything inside, except to the root ENTITY. The root ENTITY can hand references to the internal ENTITIES to other objects, but those objects can use them only transiently, and they may not hold on to the reference.

As a corrolary to the previous rule, only AGGREGATE roots can be obtained directly with database queries. All other objects must be found by traversal of associations.

Upvotes: 1

Related Questions