Design advice - When to use "virtual" and "sealed" effectively
c#, inheritance
Solution
Start with the Microsoft Design Guidelines for Developing Class Libraries, particularly the Extensibility section, where you'll find articles on virtual members and sealing.
Quoting, here:
- Do not make members virtual unless you have a good reason to do so and you are aware of all the costs related to designing, testing, and maintaining virtual members.
Do prefer protected accessibility over public accessibility for virtual members. Public members should provide extensibility (if required) by calling into a protected virtual member.
Do not seal classes without having a good reason to do so.
- Do not declare protected or virtual members on sealed types.
- Consider sealing members that you override.
Read the full articles, though.
Problem
I'm writing a C# networking library (mostly as a learning exercise, it's not overly important to me if anyone actually ends up using it as I'm sure solutions are already out there). I'm fairly happy with my structure so far... I have a few layers of client/server available, that can communicate in raw bytes over sockets, or slightly more complex through serialized message objects. The question (problem?) I'm running into is when exactly I should declare a method, property, or event `sealed`, `virtual`, or with no qualifier. I know what all of these do - `sealed` prevents inheritance of a class, or further overriding of a method. `virtual` will allow polymorphic behavior via method overriding. Since I'm designing a class library, however, I'm not sure when to use these. It's a question of extensibility, I think... I provide some interfaces, an abstract class or two, and some concrete implementations for consumers of my library to use or extend, but I'm having difficulties deciding when it's a "good idea" to explicitly forbid derivation of a class or to allow overriding functionality. Any general pointers or advice to keep in mind when designing my classes for use by others? This question and this one were somewhat helpful, as was this one, but since I'm writing a distributable library I'm trying to cover all of my bases.