Designing for Extensibility in .NET
- 6.1 Extensibility Mechanisms
- 6.2 Base Classes
- 6.3 Sealing
- Summary
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.
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.
CONSIDER using protected members for advanced customization.
Protected members are a great way to provide advanced customization without complicating the public interface.
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.
CONSIDER using callbacks to allow users to provide custom code to be executed by the framework.
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.
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.
AVOID using callbacks in performance-sensitive APIs.
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<...>).
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.
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.
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.
CONSIDER limiting extensibility to only what is absolutely necessary through the use of the Template Method Pattern, described in section 9.9.
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.
DO NOT provide abstractions unless they are tested by developing several concrete implementations and APIs consuming the abstractions.
DO choose carefully between an abstract class and an interface when designing an abstraction. See section 4.3 for more details on this subject.
CONSIDER providing reference tests for concrete implementations of abstractions. Such tests should allow users to test whether their implementations correctly implement the contract.