领域驱动设计中的验证 [英] Validation in a Domain Driven Design

查看:32
本文介绍了领域驱动设计中的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何处理领域驱动设计中复杂聚合的验证?您是否正在整合您的业务规则/验证逻辑?

How do you deal with validation on complex aggregates in a domain driven design? Are you consolidating your business rules/validation logic?

我了解参数验证和属性验证,这些验证可以附加到模型本身,并执行诸如检查电子邮件地址或邮政编码是否有效或名字是否具有最小和最大长度之类的操作.

I understand argument validation and I understand property validation which can be attached to the models themselves and do things like check that an email address or zipcode is valid or that a first name has a minimum and maximum length.

但是涉及多个模型的复杂验证呢?您通常将这些规则放在哪里?您的架构中的方法?您使用哪些模式来实现它们?

But what about complex validation that involves multiple models? Where do you typically place these rules & methods within your architecture? And what patterns if any do you use to implement them?

推荐答案

我喜欢 Jimmy Bogard 对这个问题的解决方案.他在他的博客上发表了一篇文章,标题为 使用访问者和扩展方法进行实体验证",其中他提出了一种非常优雅的实体验证方法,建议实现一个单独的类来存储验证代码.

I like Jimmy Bogard's solution to this problem. He has a post on his blog titled "Entity validation with visitors and extension methods" in which he presents a very elegant approach to entity validation that suggest the implementation of a separate class to store validation code.

public interface IValidator<T>
{
    bool IsValid(T entity);
    IEnumerable<string> BrokenRules(T entity);
}

public class OrderPersistenceValidator : IValidator<Order>
{
    public bool IsValid(Order entity)
    {
        return BrokenRules(entity).Count() == 0;
    }

    public IEnumerable<string> BrokenRules(Order entity)
    {
        if (entity.Id < 0)
            yield return "Id cannot be less than 0.";

        if (string.IsNullOrEmpty(entity.Customer))
            yield return "Must include a customer.";

        yield break;
    }
}

这篇关于领域驱动设计中的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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