C # Best Practice Inheritance

I have a normal class called BaseView with a virtual DisplayView method. This method calls GetHeader and GetBody virtual methods to retrieve the contents of the page. Then I created a class that inherits from BaseView and overrides methods that should render content differently than the way its base class is.

My problem is that although this works fine, when I run the code analysis, I warn that you are not calling the virtual functions directly.

Should I create another class of the class on top of the base class, which overrides virtual functions and only inherits from this?

What are the disadvantages of using virtual methods directly?

EDIT: warning:

CA2214: Microsoft.Usage: xxx contains a call chain that results in a call to the virtual method defined by the class. View the following call stack for unforeseen consequences

+4
source share
1 answer

I think the problem is that DisplayView is virtual and calls virtual methods. In most cases, virtual methods invoke final methods as a means of changing behavior, for example, in a strategy template. If the last method calls a virtual method, the compiler knows that the virtual method will always be called in all classes that call the output, and therefore it is valid for the virtual method to exist.

The fact that you call virtual virtual means that your design can be questioned: if the DisplayView is virtual, another implementation may override it. The current implementation calls virtual GetHeader , but the output class cannot. Therefore, it cannot guarantee that GetHeader not dead code.

This is probably what FxCop draws your attention to. He wants to know that if you define a virtual method ( GetHeader in this case) in the base class, which will use all its generating implementations.

I would focus on making DisplayView final, or evaluate your design in this light.

+4
source

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


All Articles