Can you ever have too many "protected virtual" methods?

cbp picture cbp · Nov 26, 2008 · Viewed 8k times · Source

Here's a question for those of you with experience in larger projects and API/framework design.

I am working on a framework that will be used by many other projects in the future, so I want to make it nice and extensible, but at the same time it needs to be simple and easy to understand.

I know that a lot of people complain that the .NET framework contains too many sealed classes and private members. Should I avoid this criticism and open up all my classes with plenty of protected virtual members?

Is it a good idea to make as many of my methods and properties protected virtual as possible? Under what situations would you avoid protected virtual and make members private.

Answer

Paul Sonier picture Paul Sonier · Nov 26, 2008

Your class includes data members; methods that perform basic internal operations on those data members where the functionality should never change should always be private. So methods that do basic operations with your data members such as initialization and allocation should be private. Otherwise, you run the risk of "second order" derivative classes getting an incomplete set of behaviors enabled; first derivative members could potentially redefine the behavior of the class.

That all said, I think you should be very careful with defining methods as "protected virtual". I would use great caution in defining methods as "protected virtual", because doing so not only declares the possibility of overriding the functionality, but in some ways define an expectation of overridden functionality. That sounds to me like an underdefined set of behaviors to override; I would rather have a well-defined set of behaviors to override. If you want to have a very large set of overridable behaviors, I would rather look into Aspect Oriented Programming, which allows for that sort of thing in a very structured way.