Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The key to fluent interfaces is that methods like CannotBeNull() and CannotBeBlank() return the current instance (i.e. this). If you want your AddRule method to be "fluent", instead of returning ValidationResult, you need to return the current instance of IValidator. Your extension methods would also need to return the instance of IValidator they are extending.</p> <p>I think your exact implementation might need to be a bit more complex, and hopefully the example below will provide some insight. Same general rule, however...return "this" to create a fluent interface:</p> <pre><code>interface IValidator&lt;T&gt; { IValidatorRule&lt;T, TProp&gt; AddRule&lt;TProp&gt;(Func&lt;T, TProp&gt; property); } interface IValidatorRule&lt;T&gt; { T instance { get; } string PropertyName { get; } ValidationResult Apply(T instance); } public static IValidatorAugmentorExtensions { public static IValidatorRule&lt;T&gt; CannotBeNull(this IValidatorRule&lt;T&gt; rule) { // ... return rule; } public static IValidatorRule&lt;T&gt; CannotBeBlank(this IValidatorRule&lt;T&gt; rule) { // ... return rule; } } </code></pre> <p>The above could be used like so:</p> <pre><code>public class PersonValidator: IValidator&lt;Person&gt; { public PersonValidator() { AddRule(p =&gt; p.FirstName).CannotBeNull().CannotBeEmpty(); AddRule(p =&gt; p.LastName).CannotBeNull().CannotBeEmpty(); } public List&lt;ValidationResult&gt; Validate(Person p) { List&lt;ValidationResult&gt; results = new List&lt;ValidationResult&gt;(); foreach (IValidatorRule&lt;Person&gt; rule in rules) // don't know where rules is, or what the AddRule method adds to...you'll need to figure that out { results = rule.Apply(p); } return results; } } </code></pre> <p>While the above demonstrates how to create a fluent interface, I don't really know what it buys you in the long run in this particular situation. For the convenience of a fluent interface that seems to be used only internally to concrete validators, you have increased the complexity of your code by a fair amount, without really providing a useful, fluent interface to the consumers of your validators. I would think you would glean more value by providing a fluent validation framework to the developers who need to be performing validation, rather than providing a fluent framework for creating concrete validators.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload