Hey guys,
I'm stuck with what seemed to be a very simple task at the very beginning. I have a class hierarchy each class in which can define its own validation rules. Defining validation rules should be as simple as possible. Here is what is almost what is needed:
class HierarchyBase
{
private List<Func<object, bool>> rules = new List<Func<object, bool>>();
public int fieldA = 0;
public HierarchyBase()
{
AddRule(x => ((HierarchyBase)x).fieldA % 2 == 0);
}
protected virtual void Operation()
{
fieldA++;
}
protected void AddRule(Func<object, bool> validCriterion)
{
rules.Add(validCriterion);
}
public void PerformOperation()
{
Operation();
Validate();
}
protected virtual void Operation()
{
fieldA++;
}
private void Validate()
{
IsValid = rules.All(x => x(this));
}
public bool IsValid
{
get;
private set;
}
}
There is one more thing that is needed - type safety when adding validation rules. Otherwise each sub class will have to do those casts that just look awkward. Ideally Func<T, bool>
would work, but there is a whole bunch of issues with that: we cannot inherit our HierarchyBase
from any kind of IValidatable<HierarchyBase>
as the inheritance hierarchy can be N levels deep (yeah, I feel the smell as well); storing any concrete Func<HierarchyBaseInheritor, bool>
in rules
and traversing them.
How would you introduce type-safety here?