Search code examples
c#overridingabstract-class

Overridden method in derived class


I have an abstract class with an abstract method and this class is inherited by over 100 other classes where we override this virtual method.
Now there is a slight change in business requirement and we need to do a check before calling the overridden method. I know I can put a check in each of the 100 class but that doesn't seems to be an elegant way where change is required in all derived classes.

Is there a better approach to handle this change?

public abstract class BaseFunction
{
    public abstract Result FunctionCall();
}

public class Function1 : BaseFuction
{
    public override Result FunctionCall()
    {
        //business logic
    }
}

Solution

  • You can add a wrapper method to your base class like FunctionCallWithCheck, that will perform the check, and then call the original abstract method FunctionCall.

    In order to customize the check, I put it in a virtual method with a default implementation that you can override (if needed) in derived classes.

    Note: You will have to replace all you calls to FunctionCall, with FunctionCallWithCheck (in the code that uses all these classes).
    Of course this is a good approach only if there aren't too many places where you call FunctionCall (you didn't supply info about that).

    public abstract class BaseFunction
    {
        // Default check. You can override it in derived classes if needed.
        public virtual bool Check()
        {
            return true;    // put your conditions here
        }
    
        public int FunctionCallWithCheck()
        {
            if (Check())
            {
                return FunctionCall();
            }
            return -1;
        }
    
        protected abstract int FunctionCall();
    };
    
    public class Function1 : BaseFunction
    {
        protected override int FunctionCall()
        {
            //business logic
            return 1;
        }
    };
    

    I replaced the return type to int since you did not supply the defintion for Result. I assume it has some default value in case the conditions for calling FunctionCall were not met (instead of the -1 value that I used for that).

    Update:
    As @KlausGütter commented, you can make FunctionCall into a protected method (rather than public), in order to get a compiler error if you accidently called it instead of FunctionCallWithCheck. I updated my code above.
    If you'd rather not change it because of the many derived classes, you can also keep it public (but you'll loose the compiler's protection).