DDD-唯一约束的验证 [英] DDD - Validation of unique constraint

查看:99
本文介绍了DDD-唯一约束的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在DDD中,您永远不要让您的实体进入无效状态。话虽这么说,您如何处理唯一约束的验证?



创建实体不是真正的问题。但是,假设您有一个必须具有唯一名称的实体,并且该实体类型有上千个实例-它们不在内存中,而是存储在数据库中。现在,假设您想重命名实例。



您不能只使用setter ...对象可能进入无效状态-您必须针对数据库。



如何在Web环境中处理这种情况?

解决方案

唯一性约束可以减少为持久性异常,而不是被视为无效状态。在对象保持不变之前,它不是无效状态。唯一性仅在持久性的情况下才有意义。实际上,您可以在验证机制中加入这种规则,以帮助减少发生此错误的可能性,但是在任何实际的多用户系统中,只有成功的工作单元完成持久性操作,才能保证其唯一性。 p>

因此您可能希望在验证机制中使用它,但必须在持久层中强制执行。



我通常是DDD方法的拥护者,但是我认为不允许对象进入无效状态可能需要一些曲折的抽象。在Web应用程序中,作为持久性之前的中间层,有一个单独的视图模型是一个可能的解决方案,但是我通常不会这样做,直到我确信这会比简单的替代方案减轻我的痛苦。 p>

In DDD you should never let your entities enter an invalid state. That being said, how do you handle the validation of a unique constraint?

The creation of an entity is not a real problem. But let say you have an entity that must have a unique name and there is a thousand instances of this entity type - they are not in memory but stored in a database. Now let say you want to rename an instance.

You can't just use a setter... the object could enter an invalid state - you have to validate against the database.

How do you handle this scenario in a web environment?

解决方案

A uniqueness constraint can be reduced to a persistence exception, rather than being seen as an "invalid state". It's not an invalid state until the object is persisted. Uniqueness only makes much sense in the context of persistence. Realistically, you can put this kind of rule in your validation mechanism to help reduce the likelihood of this error, but in any real multiuser system, you can't be guaranteed of uniqueness until a successful unit of work completes the persistence action.

So you may want this in your validation mechanism, but you must enforce it in your persistence layer.

I'm generally a fan of DDD as a methodology, but I think that the "don't allow objects to get into invalid states" can require some tortuous abstractions. In a web application, having a separate "View Model" is one possible solution, as an intermediary layer before persistence, but I don't usually do that until I'm convinced it will cause me less pain than the simpler alternative.

这篇关于DDD-唯一约束的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆