Should entity have methods and if so how to prevent them from being called outside aggregate

前端 未结 2 1219
醉酒成梦
醉酒成梦 2021-01-22 14:13

So, if there is an entity within an aggregate what is the best/usual way to prevent outside world from doing something like Aggregate.Entity.SomeMethod()? (in case

相关标签:
2条回答
  • 2021-01-22 14:48

    It is a question of visibility scope. It would depend on the programming language you are using. In java for example, I put an aggregate in a package. The aggregate root entity will be public. The others will have package scope, ie, no keyword for visibility.

    0 讨论(0)
  • 2021-01-22 15:01

    Aggregates should not expose data in a way that permits the aggregate's internal state to be changed from the outside.

    That means that the aggregate root object should not be handing out references to internal entities. If you want to change the state of the aggregate, you send a message to the root entity, and that logic decides whether to do the work itself or delegate it.

    Queries of the root object should return values.

    There's not much point to anemic entities -- if you are going down that road, you might as well keep things simple with value objects.

    thanks for you answer! could you just please extend an answer with: 1) does that mean that aggregate should expose copy of the entity to the outside world so that its internal entity is immutable from outside? or how does it expose it? 2) wat do you mean by 'queries of the root object should return values'?

    Short answer: you shouldn't be exposing "entities" outside of the aggregate at all.

    The motivation for entities is that they change state. The motivation for aggregates is that they coordinate changes of state among entities. If you leak an entity out of the aggregate, then the aggregate no longer has the ability to coordinate all of the changes.

    Therefore: if you want to change an aggregate, "tell, don't ask". You pass information to the aggregate root, and it will in turn create/modify the appropriate entities within the root.

    If you don't want to change an aggregate, then use a query that returns an immutable representation of the answer to the query. The precise nature of that immutable representation may vary from language to language; in the original Domain Driven Design text, the examples were taken from Java, where immutable representations are implemented using "value objects". See chapter five of the blue book.

    0 讨论(0)
提交回复
热议问题