InformIT

Designing for Extensibility in .NET

By , ,

Date: Jun 18, 2020

Sample Chapter is provided courtesy of Addison-Wesley Professional.

Return to the article

Presents issues and guidelines that are important to ensure appropriate extensibility in a .NET framework.

Save 35% off the list price* of the related book or multi-format eBook (EPUB + MOBI + PDF) with discount code ARTICLE.
* See informit.com/terms

One important aspect of designing a framework is making sure the extensibility of the framework has been carefully considered. This requires that you understand the costs and benefits associated with various extensibility mechanisms. This chapter helps you decide which of the extensibility mechanisms—subclassing, events, virtual members, callbacks, and so on—can best meet the requirements of your framework. This chapter does not cover the design details of these mechanisms. Such details are discussed in other parts of the book, and this chapter simply provides cross-references to sections that describe those details.

A good understanding of OOP is a necessary prerequisite to designing an effective framework and, in particular, to understanding the concepts discussed in this chapter. However, we do not cover the basics of object-orientation in this book, because there are already excellent books entirely devoted to the topic.

6.1 Extensibility Mechanisms

There are many ways to allow extensibility in frameworks. They range from less powerful but less costly to very powerful but expensive. For any given extensibility requirement, you should choose the least costly extensibility mechanism that meets the requirements. Keep in mind that it’s usually possible to add more extensibility later, but you can never take it away without introducing breaking changes.

This section discusses some of the framework extensibility mechanisms in detail.

6.1.1 Unsealed Classes

Sealed classes cannot be inherited from, and they prevent extensibility. In contrast, classes that can be inherited from are called unsealed classes.

// string cannot be inherited from
public sealed class String { ... }
// TraceSource can be inherited from
public class TraceSource { ... }

Subclasses can add new members, apply attributes, and implement additional interfaces. Although subclasses can access protected members and override virtual members, these extensibility mechanisms result in significantly different costs and benefits. Subclasses are described in sections 6.1.2 and 6.1.4. Adding protected and virtual members to a class can have expensive ramifications if not done with care, so if you are looking for simple, inexpensive extensibility, an unsealed class that does not declare any virtual or protected members is a good way to do it.

check.jpg 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.1 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);
  }
}

Classes are unsealed by default in most programming languages, and this is also the recommended default for most classes in frameworks. The extensibility afforded by unsealed types is much appreciated by framework users and quite inexpensive to provide because of the relatively low test costs associated with unsealed types.

6.1.2 Protected Members

Protected members by themselves do not provide any extensibility, but they can make extensibility through subclassing more powerful. They can be used to expose advanced customization options without unnecessarily complicating the main public interface. For example, the SourceSwitch.Value property is protected because it is intended for use only in advanced customization scenarios.

public class FlowSwitch : SourceSwitch {
  protected override void OnValueChanged() {
    switch (this.Value) {
      case "None" : Level = FlowSwitchSetting.None; break;
      case "Both" : Level = FlowSwitchSetting.Both; break;
      case "Entering": Level = FlowSwitchSetting.Entering; break;
      case "Exiting" : Level = FlowSwitchSetting.Exiting; break;
    }
  }
}

Framework designers need to be careful with protected members because the name “protected” can give a false sense of security. Anyone is able to subclass an unsealed class and access protected members, so all the same defensive coding practices used for public members apply to protected members.

check.jpg CONSIDER using protected members for advanced customization.

Protected members are a great way to provide advanced customization without complicating the public interface.

check.jpg DO treat protected members in unsealed classes as public for the purpose of security, documentation, and compatibility analysis.

Anyone can inherit from a class and access the protected members.

6.1.3 Events and Callbacks

Callbacks are extensibility points that allow a framework to call back into user code through a delegate. These delegates are usually passed to the framework through a parameter of a method.

List<string> cityNames = ...
cityNames.RemoveAll(delegate(string name) {
  return name.StartsWith("Seattle");
});

Events are a special case of callbacks that supports convenient and consistent syntax for supplying the delegate (an event handler). In addition, Visual Studio’s statement completion and designers provide help in using event-based APIs.

var timer = new Timer(1ʘʘʘ);
timer.Elapsed += delegate {
   Console.WriteLine("Time is up!");
};
timerStart();

General event design is discussed in section 5.4.

Callbacks and events can be used to provide quite powerful extensibility, comparable to virtual members. At the same time, callbacks—and even more so, events—are more approachable to a broader range of developers because they don’t require a thorough understanding of object-oriented design. Also, callbacks can provide extensibility at runtime, whereas virtual members can be customized only at compile-time.

The main disadvantage of callbacks is that they are more heavyweight than virtual members. The performance when calling through a delegate is worse than it is when calling a virtual member. In addition, delegates are objects, so their use affects memory consumption.

You should also be aware that by accepting and calling a delegate, you are executing arbitrary code in the context of your framework. Therefore, a careful analysis of all such callback extensibility points from the security, correctness, and compatibility points of view is required.

check.jpg CONSIDER using callbacks to allow users to provide custom code to be executed by the framework.

check.jpg CONSIDER using events, instead of virtual members, to allow users to customize the behavior of a framework without the need for understanding object-oriented design.

check.jpg CONSIDER using events instead of plain callbacks, because events are more familiar to a broader range of developers and are integrated with Visual Studio statement completion.

cross.jpg AVOID using callbacks in performance-sensitive APIs.

check.jpg DO use the Func<...>, Action<...>, or Expression<...> types instead of custom delegates when possible, when defining APIs with callbacks.

Func<...> and Action<...> represent generic delegates. The following is how .NET defines them:

public delegate void Action()
public delegate void Action<T1, T2>(T1 arg1, T2 arg2)
public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
public delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2,
 T3 arg3, T4 arg4)
public delegate TResult Func<TResult>()
public delegate TResult Func<T, TResult>(T arg)
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2)
public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2,
 T3 arg3)
public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2,
 T3 arg3, T4 arg4)

They can be used as follows:

Func<int,int,double> divide = (x,y)=>(double)x/(double)y;
Action<double> write = (d)=>Console.WriteLine(d);
write(divide(2,3));

Expression<...> represents function definitions that can be compiled and subsequently invoked at runtime but can also be serialized and passed to remote processes. Continuing with our example:

Expression<Func<int,int,double>> expression =
 (x,y)=>(double)x/(double)y;
Func<int,int,double> divide2 = expression.Compile();
write(divide2(2,3));

Notice how the syntax for constructing an Expression<> object is very similar to that used to construct a Func<> object. In fact, the only difference is the static type declaration of the variable (Expression<> instead of Func<...>).

check.jpg DO measure and understand the performance implications of using Expression<...>, instead of using Func<...> and Action<...> delegates.

Expression<...> types are, in most cases, logically equivalent to Func<...> and Action<...> delegates. The main difference between them is that the delegates are intended to be used in local process scenarios; expressions are intended for cases where it’s beneficial and possible to evaluate the expression in a remote process or machine.

check.jpg DO understand that by calling a delegate, you are executing arbitrary code, and that could have security, correctness, and compatibility repercussions.

6.1.4 Virtual Members

Virtual members can be overridden, thereby changing the behavior of the subclass. They are quite similar to callbacks in terms of the extensibility they provide, but they are better in terms of execution performance and memory consumption. Also, virtual members feel more natural in scenarios that require creating a special kind of an existing type (specialization).

The main disadvantage of virtual members is that the behavior of a virtual member can be modified only at the time of compilation. The behavior of a callback can be modified at runtime.

Virtual members, like callbacks (and maybe more than callbacks), are costly to design, test, and maintain because any call to a virtual member can be overridden in unpredictable ways and can execute arbitrary code. Also, much more effort is usually required to clearly define the contract of virtual members, so the cost of designing and documenting them is higher.

Because of the risks and costs, limiting extensibility of virtual members should be considered. Extensibility through virtual members today should be limited to those areas that have a clear scenario requiring extensibility. This section presents guidelines for when to allow it and when and how to limit it.

cross.jpg 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.

Virtual members are less forgiving in terms of changes that can be made to them without breaking compatibility. Also, they are slower than nonvirtual members, mostly because calls to virtual members are not inlined.

check.jpg CONSIDER limiting extensibility to only what is absolutely necessary through the use of the Template Method Pattern, described in section 9.9.

check.jpg DO prefer protected accessibility over public accessibility for virtual members. Public members should provide extensibility (if required) by calling into a protected virtual member.

The public members of a class should provide the right set of functionality for direct consumers of that class. Virtual members are designed to be overridden in subclasses, and protected accessibility is a great way to scope all virtual extensibility points to where they can be used.

public Control{
  public void SetBounds(...){
    ...
    SetBoundsCore (...);
  }

  protected virtual void SetBoundsCore(...){
    // Do the real work here.
  }
}

Section 9.9 provides more insight into this subject.

6.1.5 Abstractions (Abstract Types and Interfaces)

An abstraction is a type that describes a contract but does not provide a full implementation of that contract. Abstractions are usually implemented as abstract classes or interfaces, and they come with a well-defined set of reference documentation describing the required semantics of the types implementing the contract. Some of the most important abstractions in .NET include Stream, IEnumerable<T>, and Object. Section 4.3 discusses how to choose between an interface and a class when designing an abstraction.

You can extend frameworks by implementing a concrete type that supports the contract of an abstraction and then using this concrete type with framework APIs consuming (operating on) the abstraction.

A meaningful and useful abstraction that is able to withstand the test of time is very difficult to design. The main difficulty is getting the right set of members—no more and no fewer. If an abstraction has too many members, it becomes difficult or even impossible to implement. If it has too few members for the promised functionality, it becomes useless in many interesting scenarios. Also, abstractions without first-class documentation that clearly spells out all the pre- and post-conditions often end up being failures in the long term. Because of this, abstractions have a very high design cost.

Too many abstractions in a framework also negatively affect usability of the framework. It is often quite difficult to understand an abstraction without understanding how it fits into the larger picture of the concrete implementations and the APIs operating on the abstraction. Also, names of abstractions and their members are necessarily abstract, which often makes them cryptic and unapproachable without first understanding the broader context of their usage.

However, abstractions provide extremely powerful extensibility that the other extensibility mechanisms cannot often match. They are at the core of many architectural patterns, such as plug-ins, inversion of control (IoC), pipelines, and so on. They are also extremely important for testability of frameworks. Good abstractions make it possible to stub out heavy dependencies for the purpose of unit testing. In summary, abstractions are responsible for the sought-after richness of the modern object-oriented frameworks.

cross.jpg DO NOT provide abstractions unless they are tested by developing several concrete implementations and APIs consuming the abstractions.

check.jpg DO choose carefully between an abstract class and an interface when designing an abstraction. See section 4.3 for more details on this subject.

check.jpg CONSIDER providing reference tests for concrete implementations of abstractions. Such tests should allow users to test whether their implementations correctly implement the contract.

6.2 Base Classes

Strictly speaking, a class becomes a base class when another class is derived from it. For the purpose of this section, however, a base class is defined as a class designed mainly to provide a common abstraction or for other classes to reuse some default implementation though inheritance. Base classes usually sit in the middle of inheritance hierarchies, between an abstraction at the root of a hierarchy and several custom implementations at the bottom.

Base classes serve as implementation helpers for implementing abstractions. For example, one of the abstractions for ordered collections of items in .NET is the IList<T> interface. Implementing IList<T> is not trivial, so the framework provides several base classes, such as Collection<T> and KeyedCollection<TKey,TItem>, that serve as helpers for implementing custom collections.

public class OrderCollection : Collection<Order> {
  protected override void SetItem(int index, Order item) {
    if(item==null) throw new ArgumentNullException(...);
    base.SetItem(index,item);
  }
}

Base classes are usually not suited to serve as abstractions by themselves because they tend to contain too much implementation. For example, the Collection<T> base class contains lots of implementation related to the fact that it implements the non-generic IList interface (to integrate better with non-generic collections) and to the fact that it is a collection of items stored in memory in one of its fields.

As previously discussed, base classes can provide invaluable help for users who need to implement abstractions, but at the same time they can be a significant liability. They add surface area and increase the depth of inheritance hierarchies, thereby conceptually complicating the framework. For this reason, base classes should be used only if they provide significant value to the users of the framework. They should be avoided if they provide value only to the implementers of the framework, in which case delegation to an internal implementation instead of inheritance from a base class should be strongly considered.

check.jpg CONSIDER making base classes abstract even if they don’t contain any abstract members. This clearly communicates to the users that the class is designed solely to be inherited from.

check.jpg CONSIDER placing base classes in a separate namespace from the mainline scenario types. By definition, base classes are intended for advanced extensibility scenarios and are not interesting to the majority of users. See section 2.2.4 for details.

cross.jpg AVOID naming base classes with a “Base” suffix if the class is intended for use in public APIs.

For example, despite the fact that Collection<T> is designed to be inherited from, many frameworks expose APIs typed as the base class, not as its subclasses, mainly because of the cost associated with a new public type.

public Directory {
  public Collection<string> GetFilenames(){
     return new FilenameCollection(this);
     }

  private class FilenameCollection : Collection<string> {
     ...
  }
}

The fact that Collection<T> is a base class is irrelevant for the user of the GetFilename method, so the “Base” suffix would simply create an unnecessary distraction for the user of the method.

6.3 Sealing

One of the features of object-oriented frameworks is that developers can extend and customize them in ways unanticipated by the framework designers. This is both the power and the danger of extensible design. When you design your framework, it is very important to carefully design for extensibility when it is desired, and to limit extensibility when it is dangerous.

Sealing is a powerful mechanism that prevents extensibility. You can seal either the class or individual members. Sealing a class prevents users from inheriting from the class. Sealing a member prevents users from overriding a particular member.

public class NonNullCollection<T> : Collection<T> {
   protected sealed override void SetItem(int index, T item) {
    if(item==null) throw new ArgumentNullException();
     base.SetItem(index,item);
  }
}

Because one of the key differentiating points of frameworks is that they offer some degree of extensibility, sealing classes and members will likely feel very abrasive to developers using your framework. Therefore, you should seal only when you have good reasons to do so.

cross.jpg DO NOT seal classes without having a good reason to do so.

Sealing a class because you cannot think of an extensibility scenario is not a good reason. Framework users like to inherit from classes for various nonobvious reasons, such as adding convenience members. See section 6.1.1 for examples of nonobvious reasons users want to inherit from a type.

Good reasons for sealing a class include the following:

cross.jpg DO NOT declare protected or virtual members on sealed types.

By definition, sealed types cannot be inherited from. This means that protected members on sealed types cannot be called, and virtual methods on sealed types cannot be overridden.

check.jpg CONSIDER sealing members that you override.

public class FlowSwitch : SourceSwitch {
  protected sealed override void OnValueChanged() {
    ...
  }
}

Problems that can result from introducing virtual members (discussed in section 6.1.4) apply to overrides as well, although to a slightly lesser degree. Sealing an override shields you from these problems starting from that point in the inheritance hierarchy.

In short, part of designing for extensibility is knowing when to limit it, and sealed types are one of the mechanisms by which you do that.

Summary

Designing for extensibility is a critical aspect of designing frameworks. Understanding the costs and benefits provided by various extensibility mechanisms permits the design of frameworks that are flexible while avoiding many of the pitfalls that could lead to trouble later.

800 East 96th Street, Indianapolis, Indiana 46240