I'm currently working on MVC controls that are using a fluent API for the construction. I have no troubles with that for the moment.
But every method in my fluent API does take a parameter. According to that parameter, a property is set.
For Example:
var grid = GridFor<Model>(items).WithName("MyName").WithRowHeader("true");
But now I'm wondering how a fluent API does work when you have methods that doesn't take for a parameter.
For example:
var result = Model.Validate(x => x.Age).When().It().Is().Any().Number();
More in detail, I'm struggling with an approach like this:
string s = "Hello";
s.Validate().It().Is().String();
s.Validate().It().Is().No().String();
I'm having difficulties here on how the String method would know if it should validate the given object to see if it's a string or not. I guess I need to pass the whole chain into it and based on the chain execute my logic?
Can someone provide me some guidance on how something like that should and can be accomplished?
It works a bit like this:
public static class ValidationExtensions
{
public static Validation<T> Validate<T>(this T source)
{
return new Validation<T>(source);
}
}
public class Validation<T>
{
private readonly T valueToValidate;
public Validation(T value)
{
valueToValidate = value;
}
public void Is<T>(T value)
{
if (!Object.Equals(valueToValidate, value))
throw new Exception();
}
public NegativeValidation<T> Not()
{
return NegativeValidation(value);
}
}
public class NegativeValidation<T>
{
private readonly T valueToValidate;
public NegativeValidation(T value)
{
valueToValidate = value;
}
public void Is<T>(T value)
{
if (Object.Equals(valueToValidate, value))
throw new Exception();
}
public NegativeValidation<T> Not()
{
return Validation(value);
}
}
string s = "Hello World";
s.Validate().Is("Hello World");
s.Validate().Not().Is("Hello World"); // exception
s.Validate().Not().Not().Is("Hello World");