Override method - to call an overridden implementation (super) or not to call?

Is there any rule of thumb for this decision? I have always adhered to this question. Even if I know that at present I do not need the result of the overriden method, how can I be sure that the overriden method will not be changed in the future? For example, there is a possibility that the author of the parent class that I am producing will decide to implement some side effect in the method that I redefine, and without this side effect the state of the object will be wrong.

+3
source share
4 answers

IMO, the default solution should always call the superclass and then handle any other behavior. This applies to all the reasons you are talking about (it may be needed now, but if not, it may be needed in the future).

The only exception is when you KNOW in advance that the superclass will do what you specifically do not want. But in any case, these problems indicate design problems. It is very suspicious to see subclasses without calling them parents.

+3
source

There are two main reasons for invoking an implementation of a base class in overriding one of its methods:

You want to extend the behavior of the base class.

. , , .

, , .

. , , , , .

, , , . , - . :

class Car{
    bool engineRunning;

    public virtual void StartEngine(){
        TurnIgnitionKey();
        engineRunning = true; // this is the internal side effect
    }
    public void DriveAround(){
        if(!engineRunning)
            throw new InvalidOperationException("You have to start the engine first.");

        // implement driving around
    }
}

class S2000 : Car{
    public override void StartEngine(){
        PushStartButton();
    }
}

, S2000 StartEngine() Car, DriveAround() . Car , S2000, , , StartEngine.

Car . - :

class Car{
    bool engineRunning;

    public void StartEngine(){ // not virtual
        StartEngineInternal();
        engineRunning = true;
    }
    protected virtual void StartEngineInternal(){
        TurnIgnitionKey();
    }
}

, -, . , , , , , .

+3

. , - / .

+1

STL . , . , ( ).

- -, ​​, . . , std:: streambuf.

In this way, a base class developer can also achieve Alexandrescu's recommendation not to publish virtual functions.

0
source

Source: https://habr.com/ru/post/1716304/


All Articles