I was stuck in what seemed like a very simple task at the very beginning. I have a hierarchy of classes, each of which can define its own validation rules. Defining verification rules should be as simple as possible. Here is what you need:
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;
}
}
One more thing is required - enter security when adding validation rules. Otherwise, each subclass will have to perform those videos that look uncomfortable. It Func<T, bool>will work ideally , but there are a number of problems with this: we cannot inherit ours HierarchyBasefrom any type IValidatable<HierarchyBase>, since the inheritance hierarchy can be N levels deep (yes, I also smell); keeping any concrete Func<HierarchyBaseInheritor, bool>in rulesand moving them.
?