Working with Aggregates in DDD
Looking for some clarification on working with aggregate roots.
If I have a model (a question paper) as follows;
QUESTION PAPER ---> QUESTION ---> ANSWER
and I have identified that the QUESTION PAPER is an aggregate root, if I want to select a answer for a question do I have to put a public method on the aggregate root or 开发者_StackOverflow社区can I expose the questions from the root and put a public method on the QUESTION object to select a ANSWER??
In general you always want to be talking to your aggregate root. If you're reading values then sometimes it can be convenient to add public accessors to aggregates inside the aggregate root, but it gets ugly (Law of Demeter, breaking abstractions, etc, etc) very quickly and I would suggest that you don't do it.
For anything that changes state, however, it's critical that you always go through the aggregate root. The aggregate root represents a consistency boundary (i.e. it is responsible, either directly or indirectly, for keeping things in a valid state) and if you allow state changes you bypass this altogether, opening the door to ever increasing complexity.
So, it depends what you mean by 'select' in your question - if you're querying then you can get away with it, but it's a bad idea. If you are changing state then don't do it, or your aggregate root is no longer an aggregate root.
精彩评论