DDD使用规范模式进行验证 [英] DDD Using Specification pattern for Validation

查看:81
本文介绍了DDD使用规范模式进行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑将规范模式用于验证目的。困难的是如何告诉用户为什么不满足某些规范。如果 Specification.IsSatisfiedBy()不仅会返回 bool 值,还会返回失败原因。看起来像这样:

I am thinking of using Specification pattern for validation purposes. The hard thing is how to tell the user why some Specification was not satisfied. What if the Specification.IsSatisfiedBy() will not only return a bool value, but also the reason of failure. It would look something like this:

interface ISpecification<T>
{
  CheckResult IsSatisfiedBy(T candidate);
}

其中 CheckResult 为:

class CheckResult
{
  public bool IsSatisfied { get; }
  public string FailureReason { get; }
}

福勒&埃文斯(Evans)的工作中有一个部分满足的规范的概念,其目的是提供解释到底是什么不满足。但是,在该文档中,它是作为其他方法 remainderUnsatisfiedBy 实现的,该方法返回的规范不是候选人完成的规范。

In Fowler & Evans work there is a concept of Partially Satisfied Specification whose purpose is to provide explanation what exactly was not satisfied. However in that document, it is implemented as additional method remainderUnsatisfiedBy which returns the Specification which was not accomplished by the Candidate.

问题是:当使用规范进行验证时,如何向用户提供不满足给定规范的反馈?我上面介绍的解决方案好吗?

So the question is: When using Specification for validation purposes, how to provide feedback to user that a given Specification was not satisfied? Is the solution I've presented above good?

推荐答案

尽管您可以使用Specification类进行验证,但我建议您保留将它们作为您域中的独立概念。您可能会发现您需要重复使用相同的基础规范,但需要根据目的和上下文返回不同的失败原因。请参阅这篇文章了解更多详细信息。

Although you may use your Specifications classes for validation, I would suggest you keep them as separate concepts within your domain. You may find that you need to re-use the same underlying specifications but need to return different "Failure Reasons" depending on purpose and context. See this article for more details.

上面引用的帖子的作者也将代码共享给了github,并发布了代码为NCommon。尤其要检查以下方面:

The author of the post referenced above has also kindly shared code to github and posted the code as NCommon. Review these areas in particular:

规格 https://github.com/riteshrao/ncommon/tree/v1.2/NCommon/src/Specifications

验证 https://github.com/riteshrao/ncommon/tree/v1.2/NCommon/src/Rules (尤其是 ValidationResult ValidationError 的类)

这篇关于DDD使用规范模式进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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