Task:

There is a base class that implements some kind of common functionality used by most children.

But. There are some descendants for which this common functionality should be disabled.

I see three options for solving this problem:

  1. Internal protected variable in the base class, depending on which the necessary functionality will or will not be executed. The value of this variable sets the base class by default, and the children can change.
  2. A virtual method of the base class, depending on the return value of which the necessary functionality will or will not be performed. The default value returns the base class method. A child can override this method and return the value it needs.
  3. The general functionality is carried out in one virtual protected not sealed method. A descendant, if necessary, can override this method, completely removing or changing the desired behavior.

Which solution is better?

Maybe there are other solutions?

  • one
    It would be cleaner to introduce another class into the hierarchy in which this functionality does not exist. - Igor
  • Igor, Changing the hierarchy implies branching inheritance. In this task, the change in the hierarchy is not considered, since inheritance must be from the same base class without branching. - Andrey Tumanov

1 answer 1

As an option, you override the method of the base class from the descendant, the functionality of which you want to remove, and make it empty. I often see such a solution.

  • By the way, this refers to the concept of polymorphism - Goncharov Alexander
  • Thank. Added a third solution to the question description. - Andrey Tumanov