Why should virtual functions not be used excessively?

前端 未结 10 2068
再見小時候
再見小時候 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

    I dont know where you read that, but imho this is not about performance at all.

    Maybe its more about "prefer composition about inheritance" and problems which can occur if your classes/methods are not final (im talking mostly java here) but not really designed for reuse. There are many things which can go really wrong:

    • Maybe you use virtual methods in your constructor - once theyre overridden, your base class calls the overridden method, which may use ressources initialized in the subclass constructor - which runs later (NPE rises).

    • Imagine an add and an addAll method in a list class. addAll calls add many times and both are virtual. Somebody may override them to count how many items have been added at all. If you dont document that addAll calls add, the developer may (and will) override both add and addAll (and add some counter++ stuff to them). But now, if you youse addAll, each item is count twice (add and addAll) which leads to incorrect results and hard to find bugs.

    To sum this up, if you dont design your class for being extended (provide hooks, document some of the important implementation things), you shouldnt allow inheritance at all because this can lead to mean bugs. Also its easy to remove a final modifier (and maybe redesign it for reuseability) from one of your classes if needed, but its impossible to make a non-final class (where subclassing lead to errors) final because others may have subclassed it already.

    Maybe it was really about performance, then im at least off topic. But if it wasnt, there you have some good reasons not to make your classes extendable if you dont really need it.

    More information about stuff like that in Blochs Effective Java (this particular post was written a few days after I read item 16 ("prefer composition over inheritance") and 17 ("design and document for inheritance or else prohibit it") - amazing book.

提交回复
热议问题