将子实体添加到聚合根的推荐方法是什么?
哪种方法更好,首先创建子实体,然后传递到聚合根来添加它们,还是让聚合根创建它们?例如:
Order.AddOrderLine(new OrderLine(product, quantity, ...));
或者
Order.AddOrderLine(product, quanity, ...);
哪种方法更好?我确信这纯粹是主观的,但我想看看哪个有更多的优点和缺点。
Which is a better approach, create child entities first, then pass to the aggregate root to add them, or have the aggregate root create them? For example:
Order.AddOrderLine(new OrderLine(product, quantity, ...));
Or
Order.AddOrderLine(product, quanity, ...);
Which is a better approach? I'm sure this is purely subjective, but I want to see which has more pros vs cons.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,基本上我的观点是您应该之前创建一个对象,因为:
创建对象本身就是一个单独的问题,顺便说一句,这可能相当复杂。例如,如果稍后将更改
OrderLine
的构造函数,您也需要更改Order
类型。这很糟糕,因为您只需要更改Order
就可以了,因为OrderLine
发生了一些变化。因此,Order
根的接口不应该依赖于OrderLine
。第二种方法可能很难测试,如果您的方法将包含一些额外的逻辑,除了仅调用
this.OrderLines.Add(orderLine);
Edit
在和我的一个朋友讨论这个问题后,我得出了以下观点:
Order Root 应该控制他的孩子的生命周期,因为这对于使用这个 API 的其他人来说会更清楚,并且会最大限度地减少不适当的可能性用法。并且也能更好地揭示意图。
使用这种方法还允许我们不必担心验证传入的 OrderLine,因为如果我们负责 OrderLine 的创建,那么我们就可以正确创建它。
Ok, so basically my opinion is that you should create an object before, because:
creating of the object is itself a separate concern, which can be a fairly complex by the way. And if, for instance, constructor of the
OrderLine
will be changed later you will need to change anOrder
type too. This is bad, cos you will need to change theOrder
only because of some changes in theOrderLine
. So interface of theOrder
Root shouldn't depend on theOrderLine
.the second approach may be hard to test if you method will contain some additional logic exept of only calling
this.OrderLines.Add(orderLine);
Edit
After discussing this with a friend of mine, I came up with the following opinion:
Order Root should control lifetime of his child, because this will be more clear for other person who uses this API and will minimize the possibility of an inappropriate usage. And also will better reveal intent.
Using this approach also allows us not to worry about validating incoming OrderLine, because if we are responsible of the OrderLine creation then we can create it properly.