Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

c# - Specification Pattern vs (Fluent) Validation

What is different between Specification Pattern and (Fluent) Validation? Are they similar?

// 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);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your two examples are both doing validation, but are stylistically different.

The first uses inheritance and composition to to specify how the validation is performed, overriding a method to contain the validation logic. This is what most would consider an instance of the Specification Pattern.

The second uses a flatter structure (though it doesn't have to) and a RuleFor() specification that takes the validation logic as an expression to be executed against some subject. This isn't an instance of the Specification Pattern, but you can argue it is a specification pattern as the RuleFor() is a declarative statement (or specification) of what to do.

Though the latter has "Fluent" in it's name, that's for a different reason: it relies on the fluent interface style of programming. You can see that in your example because it uses method chaining with the RuleFor() returning an object where GreaterThanOrEqualTo() is invoked immediately without assigning the result of RuleFor() to a temp variable.

EDIT: In practice, I've more often seen the specification pattern used in DDD because each specification can communicate an important domain validation or constraint very clearly just through the name of the specification. In practice, I've seen the second validation pattern more often used for user inputs prior to hydrating the domain.

This is totally anecdotal, and by no means an absolute rule.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...