规范模式与(流畅的)验证
Specification Pattern vs (Fluent) Validation
Specification Pattern
和 (Fluent) Validation
有什么区别?它们相似吗?
// Specification
public class PremiumSpecification<T> : CompositeSpecification<T>
{
private int cost;
public PremiumSpecification(int cost) {
this.cost = cost;
}
public override bool IsSatisfiedBy(T o) {
return (o as Mobile).Cost >= this.cost; // HERE
}
}
// Fluent Validation
public class CustomerValidator : AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Cost).GreaterThanOrEqualTo(0);
}
}
您的两个示例都在进行验证,但风格不同。
第一个使用继承和组合来指定验证的执行方式,覆盖包含验证逻辑的方法。这是大多数人会考虑 the Specification Pattern.
的实例
第二个使用更扁平的结构(虽然它不是必须的)和一个 RuleFor()
规范,该规范将验证逻辑作为要针对某些主题执行的表达式。这不是 the 规范模式的一个实例,但你可以说它是 a 规范模式,因为 RuleFor()
是一个声明做什么的声明(或规范)。
虽然后者的名称中有“Fluent”,但这是出于不同的原因:它依赖于 fluent interface style of programming. You can see that in your example because it uses method chaining 和 RuleFor()
返回一个对象,其中 GreaterThanOrEqualTo()
被立即调用没有将 RuleFor()
的结果分配给临时变量。
编辑:在实践中,我更经常看到 DDD 中使用的规范模式,因为每个规范都可以通过 name 非常清楚地传达重要的域验证或约束规范。在实践中,我已经看到第二种验证模式更常用于在对域进行水合之前的用户输入。
这完全是轶事,绝不是绝对规则。
Specification Pattern
和 (Fluent) Validation
有什么区别?它们相似吗?
// Specification
public class PremiumSpecification<T> : CompositeSpecification<T>
{
private int cost;
public PremiumSpecification(int cost) {
this.cost = cost;
}
public override bool IsSatisfiedBy(T o) {
return (o as Mobile).Cost >= this.cost; // HERE
}
}
// Fluent Validation
public class CustomerValidator : AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Cost).GreaterThanOrEqualTo(0);
}
}
您的两个示例都在进行验证,但风格不同。
第一个使用继承和组合来指定验证的执行方式,覆盖包含验证逻辑的方法。这是大多数人会考虑 the Specification Pattern.
的实例第二个使用更扁平的结构(虽然它不是必须的)和一个 RuleFor()
规范,该规范将验证逻辑作为要针对某些主题执行的表达式。这不是 the 规范模式的一个实例,但你可以说它是 a 规范模式,因为 RuleFor()
是一个声明做什么的声明(或规范)。
虽然后者的名称中有“Fluent”,但这是出于不同的原因:它依赖于 fluent interface style of programming. You can see that in your example because it uses method chaining 和 RuleFor()
返回一个对象,其中 GreaterThanOrEqualTo()
被立即调用没有将 RuleFor()
的结果分配给临时变量。
编辑:在实践中,我更经常看到 DDD 中使用的规范模式,因为每个规范都可以通过 name 非常清楚地传达重要的域验证或约束规范。在实践中,我已经看到第二种验证模式更常用于在对域进行水合之前的用户输入。
这完全是轶事,绝不是绝对规则。