Framework Design Guidelines: Sealed Classes

Continuing in our weekly blog post series that highlights a few of the new image5_thumb2_thumb2_thumb_thumb_thu_thumb_thumb_thumbadditions to the Framework Design Guidelines 2nd edition.. This content is found in the Extensibility Mechanisms section of Chapter 6: Designing for Extensibility. It is interesting to watch as new development methodologies become more popular and how the color the guidelines…

CONSIDER using unsealed classes with no added virtual or protected members as a great way to provide inexpensive yet much appreciated extensibility to a framework.

Developers often want to inherit from unsealed classes so as to add convenience members such as custom constructors, new methods, or method overloads. For example, System.Messaging.MessageQueue is unsealed and thus allows users to create custom queues that default to a particular queue path or to add custom methods that simplify the API for specific scenarios (in the following example, the scenario is for a method sending Order objects to the queue).

public class OrdersQueue : MessageQueue {
   public OrdersQueue() : base(OrdersQueue.Path){
      this.Formatter = new BinaryMessageFormatter();
   }

   public void SendOrder(Order order){
      Send(order,order.Id);
   }
}

PHIL HAACK

Because Test Driven Development has caught fire in the .NET Developer community, many developers want to inherit from unsealed classes (often dynamically using a mock framework) in order to substitute a test double in the place of the real implementation.

At the very least, if you’ve gone to the trouble of making your class unsealed, consider making key members virtual, perhaps via the Template Method Pattern, in order to provide more control.