重构在if语句中产生返回

本文关键字:返回 语句 if 重构 | 更新日期: 2023-09-27 18:18:01

在一个项目中,我有一组验证器对象,其中Validate yield为每个错误返回一个ValidationResult。然后,收集这些数据并抛出异常。验证:如何用Ninject注入模型状态包装器?

当需要验证的对象具有复杂的属性也需要验证时,我最终会得到像这样的笨拙代码(我的问题是foreach循环):

public class MembershipValidator
{
    public override IEnumerable<ValidationResult> Validate(Membership entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        }
        foreach (var result in userValidator.Validate(entity.User))
        {
            yield return result;
        }
    }
}

在这种情况下,UserValidator也有几个yield return语句(其中一个在这里显示):

public class UserValidator
{
    public override IEnumerable<ValidationResult> Validate(User entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException();
        }
        if (entity.BirthDate == DateTime.MinValue)
        {
            yield return new ValidationResult("User", "BirthDate is mandatory");
        }
    }
}

是否有办法在"父"验证器中编写更简洁的代码?它现在充满了foreach循环。简单地编写以下代码构建,但不执行:

userValidator.Validate(entity.User);

下面的代码不能编译:

return userValidator.Validate(beschouwing.User);

重构在if语句中产生返回

只拆分参数检查(即抛出异常)并在两个方法中生成验证结果:

public override IEnumerable<ValidationResult> Validate(User entity)
{
    if (entity == null)        
        throw new ArgumentNullException();        
    return UserValidationIterator(entity);
}
private IEnumerable<ValidationResult> UserValidationIterator(User user)
{
    if (entity.BirthDate == DateTime.MinValue)
       yield return new ValidationResult("User", "BirthDate is mandatory");
    // other yields here
}

您可以对成员验证使用相同的方法