Monday, May 17, 2004
« MFC to .NET Rollercoaster | Main | Good Cop, Good Cop »

Eric Gunnerson brings up an interesting point on which I'd like to elaborate regarding virtual methods.  It has long been a tenet of mine in the realm of object design that the programmer should be in full control of his components and their usage.  The developer of a component knows (or should know) intimately the inner workings of his components.  When an object is designed, the methods thereon should provide the consumer (another developer) with a direction and a usage.  Classes should readily make apparent their intended usage - if it's not really a possibility, then better documentation should be made available.  This helps avoid problems wherein another developer uses the class in an unsupported manner.

I am a strong believer that methods should not be virtual (overridable for the not-so-strong-right-pinkied folk out there).  When a method is marked as virtual it shouts out to the deriver that it was the developers intentions to support scenarios in which the method is overridden.  As EricGu points out, marking everything as virtual to handle the fringe case of 'just in case the developer wants to extend the functionality' is poor design and very non-intuitive.

I take it a step further in all of my design.  I believe that a class should be marked as sealed by default.  By doing so, the developers intentions are clear: You cannot override this class, it will simply not be tolerated!  I make it a practice, in fact, to mark all classes that I create 'internal sealed' to enforce this pattern.  Only in situations in which I am intentionally designing a class to be overridden do I remove the sealed class (e.g. when there is at least one virtual function).  Only when the class is intended to be used externally to my component to I mark them as public.  To help enforce this practice, I've taken the time to edit each of the VS.NET templates if anyone would like them.

This practice has saved me hours of headache and has enforced a logical design and structure to my components.

Thoughts? Comments?

Monday, May 17, 2004 12:43:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [2]  |  Trackback