Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally block method override

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?

like image 397
agentshowers Avatar asked Dec 18 '15 12:12

agentshowers


1 Answers

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.

like image 145
Patrick Hofman Avatar answered Sep 22 '22 05:09

Patrick Hofman