Why should virtual functions not be used excessively?

前端 未结 10 2107
再見小時候
再見小時候 2021-02-19 13:16

I just read that we should not use virtual function excessively. People felt that less virtual functions tends to have fewer bugs and reduces maintenance.

What kind of b

10条回答
  •  执念已碎
    2021-02-19 13:32

    You've posted some blanket statements that I would think most pragmatic programmers would shrug off as being misinformed or misinterpreted. But, there do exist anti-virtual zealots, and their code can be just as bad for performance and maintenance.

    In Java, everything is virtual by default. Saying you shouldn't use virtual functions excessively is pretty strong.

    In C++, you must declare a function virtual, but it's perfectly acceptable to use them when appropriate.

    I just read that we should not use virtual function excessively.

    It's hard to define "excessively"... certainly "use virtual functions when appropriate" is good advice.

    People felt that less virtual functions tends to have fewer bugs and reduces maintenance. I'm not able to get what kind of bugs and disadvantages can appear due to virtual functions.

    Poorly designed code is hard to maintain. Period.

    If you're a library maintainer, debugging code buried in a tall class hierarchy, it can be difficult to trace where code is actually being executed, without the benefit of a powerful IDE, it's often hard to tell just which class overrides the behavior. It can lead to a lot of jumping around between files tracing inheritance trees.

    So, there are some rules of thumb, all with exceptions:

    • Keep your hierarchies shallow. Tall trees make for confusing classes.
    • In c++, if your class has virtual functions, use a virtual destructor (if not, it's probably a bug)
    • As with any hierarchy, keep to a 'is-a' relationship between derived and base classes.
    • You have to be aware, that a virtual function may not be called at all... so don't add implicit expectations.
    • There's a hard-to-argue case to be made that virtual functions are slower. It's dynamically bound, so it's often the case. Whether it matters in most of the cases that its cited is certainly debatable. Profile and optimize instead :)
    • In C++, don't use virtual when it's not needed. There's semantic meaning involved in marking a function virtual - don't abuse it. Let the reader know that "yes, this may be overridden!".
    • Prefer pure virtual interfaces to a hierarchy that mixes implementation. It's cleaner and much easier to understand.

    The reality of the situation is that virtual functions are incredibly useful, and these shades of doubt are unlikely coming from balanced sources - virtual functions have been widely used for a very long time. More newer languages are adopting them as the default than otherwise.

提交回复
热议问题