实现相同接口的多个类中需要验证

时间:2018-05-27 13:58:18

标签: c# inheritance design-patterns method-overriding

我有以下界面:

public interface IFoo
{
    void DoSmth(IList<int> list, string path);
}

还有多个派生类实现此接口及其单个方法。所有类都需要首先验证输入参数,然后才进行实际工作。应该在哪里进行验证?

一种解决方案是在每个派生类中编写验证代码,这会导致代码重复。

第二个更好的解决方案是使用抽象基类并在那里执行所有验证。像这样:

public abstract class BaseFoo
{
    public void DoSmth(IList<int> list, string path)
    {
        if(list == null)
        {
            throw new ArgumentNullException(nameof(list));
        }

        if(list.Count < 3)
        {
            return;
        }

        ...
        // more validation here
        ...

        InnerDoSmth(list, path);
    }

    protected abstract void InnerDoSmth(IList<int> list, string path);
}

此案例是否有任何设计模式和最佳做法?或者可以使用基类?

那么我应该在哪里放置验证码?

1 个答案:

答案 0 :(得分:1)

通常我会使用单独的验证器类来验证每个用例。例如。在将产品添加到数据库之前,我将使用AddProductValidator来验证业务规则,在删除产品之前,我将使用DeleteProductValidator进行验证等。可以将公共业务规则提取到规范类(规范模式)并由验证器类共享

要构建验证器类,我遵循以下方法:http://lostechies.com/jimmybogard/2007/10/24/entity-validation-with-visitors-and-extension-methods/

由于您使用.NET,我认为您可能需要考虑Fluent验证(https://github.com/JeremySkinner/FluentValidation)。我认为这很酷,非常接近我上面提到的文章