Saturday, November 6, 2010

Factoring Out Common Patterns in Libraries

A well designed core library is essential for building concise, maintainable programs in any programming language. There are many common, recurrent patterns when writing code, and ideally, these recurring uses should be factored into their own abstractions that are distributed as widely as possible throughout the core library.

Consider for instance, an "encapsulated value" pattern:
/// <summary>
/// A read-only reference to a value.
/// </summary>
/// <typeparam name="T">The type of the encapsulated value.</typeparam>
public interface IValue<T>
{
/// <summary>
/// A read-only reference to a value.
/// </summary>
T Value { get; }
}

This shows up everywhere, like Nullable<T>, Lazy<T>, and Task<T> (property called "Result"), IEnumerator<T> (property called "Current"), and many many more.

However, the common interface of a value encapsulated in an object has not been factored out into a common interface in the .NET Base Class Library (BCL). This means one cannot write programs that are agnostic over the type of a value's container, resulting in unnecessary code duplication.

A legitimate argument against this approach is that the containers each have different semantics. For instance, accessing Lazy.Value will block until the value becomes available, but Nullable.Value always returns immediately.

Fortunately, this is not an argument against factoring out the "encapsulated value" pattern, but an argument for another interface that exposes these semantics. In this case, the new pattern is an "optional value":
/// <summary>
/// A volatile value.
/// </summary>
/// <typeparam name="T">The type of value held in the reference.</typeparam>
public interface IVolatile<T>
{
/// <summary>
/// Attempt to extract the value.
/// </summary>
/// <param name="value">The value contained in the reference.</param<
/// <returns>True if the value was successfully retrieved, false otherwise.</returns>
bool TryGetValue(out T value);
}
public interface IOptional<T> : IValue<T>, IVolatile<T>
{
/// <summary>
/// Returns true if a value is available.
/// </summary>
bool HasValue { get; }
}

Lazy, Nullable and Task all exhibit these exact semantics. Programs can then be written that are agnostic over how optional values are encapsulated and processed, and the common interfaces ensure the different behaviours are overloaded in a consistent, familiar way.

We can extend this even further to "mutable encapsulated values, aka, references":
/// <summary>
/// A mutable reference.
/// </summary>
/// <typeparam name="T">The type of value the reference contains.</typeparam>
public interface IRef<T> : IValue<T>
{
/// <summary>
/// The value in the reference.
/// </summary>
new T Value { get; set; }
}

This pattern is less common, but still quite prevalent. For instance, see ThreadLocal<T> (which could also implement IOptional and IVolatile incidentally).

These interfaces have been in the Sasa library for quite some time, and are used consistently throughout the entire library. The consistency has helped considerably in guiding the design of new abstractions, and clarifying their use, since developers can simply understand any new abstraction in terms of the familiar interfaces it implements.

I suppose the lesson to take from all this is to hunt down common patterns, and aggressively factor them out into reusable abstractions. This helps the library's consistency, thus helping clients learn your API by reducing the number of unnecessary new properties and methods.

4 comments:

alexey-rom said...

Too bad we don't have typeclasses in .Net, which would enable us to factor out the similarities which BCL authors didn't.

Sandro Magi said...

Agreed! We can sort of get around it though, in a similar way to how I circumvented C#'s inability to specify Delegate, Enum, etc. as type constraints: a wrapper class and IL rewriting to erase the wrapping, and generate code for all the cases.

It's not nearly as pretty as type classes though.

Qwertie said...

At least two new languages, Go and Rust, solve the problem of "a type that you can't change doesn't explicitly implement an interface, but has all the methods of the interface". Go interfaces are sorely missed in the .NET framework, since common collection patterns like IEnumerable+Count and IEnumerable+Count+indexer have no interface; and most collection classes that were written for .NET 1.0 still don't implement any generic interfaces at all.

I made a general solution at http://www.codeproject.com/Articles/87991/Dynamic-interfaces-in-any-NET-language

... but because it's relatively heavyweight, using a dynamic assembly and all, and because I'm a performance freak, I still tend to write specialized wrappers for common cases.

Sandro Magi said...

What you're after are ad-hoc extensions. I explained how to achieve ad-hoc extensions in another post.

P.S. sorry for the double-post, chrome ad-blocker ate my first link.