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

前端 未结 2 1220
醉酒成梦
醉酒成梦 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 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.

提交回复
热议问题