I have an application where the parent object has a method to perform validations and every child overrides the method to perform extra validations. Something like:
class Parent {
    virtual void DoValidations (Delegate addErrorMessage) {
        //do some validations
    }
}
class Child : Parent {
    override void DoValidations (Delegate addErrorMessage) {
         base.DoValidations(addErrorMessage); //the parent method is always called
         //do some extra validations
   }
}
I added a new "IsDisabled" property that when true the method will not perform any validations.
class Parent {
    boolean IsDisabled;
    virtual void DoValidations (Delegate addErrorMessage) {
        if (IsDisabled)
            return;
        //do some validations
    }
}
I also want that for every child, if the "IsDisabled" property is true, the extra verifications aren't performed. What is the better pattern to use here?
I would split that functionality off in a separate method:
private void DoValidations(Delegate addErrorMessage)
{
    if (!this.IsDisabled)
    {
        this.OnDoValidations(addErrorMessage);
    }
}
virtual void OnDoValidations(Delegate addErrorMessage) { }
Now, OnDoValidations can be overridden at will. The IsDisabled check will be done inside the base class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With