Wednesday, February 27, 2008

Guarding with extension methods

I came up with a little - as far as I'm concerned - cool library consisting of extension methods used to guard input parameters of public methods.

It's always a good idea to validate arguments of public methods and throw exceptions if the validation fails. If you require that a parameter is not null, throw an "ArgumentNullException" if the specified argument is null, this makes debugging so much easier and helps other developers that uses your API. To do this in all public methods is a painstaking and repetitive job but my little library makes it just a bit easier.

For example to validate that the string argument of the following method is not null or empty we'd have to write code something like this:

public static char Foo(string bar)
{
    if (bar == null)
        throw new ArgumentNullException("bar");
    if (bar.Length == 0)
        throw new ArgumentOutOfRangeException("bar");

    return bar[0];
}

Now with my extension methods you'd instead write the following:

public static char Foo(string bar)
{
    bar.ExceptionIfNullOrEmpty("bar");
    return bar[0];
}

We can perform other validations as well, for example, we can validate that a value is within a given range:

public static bool Foo(int i)
{
    // The parameter "i" must be within the range 0-10
    i.ExceptionIfOutOfRange(0, 10, "i"); 
}

By using generics and generic constraints the extension methods only appear on values of types they are applicable to. For example the method that checks if a value is within a specified range is only applicable to values of types that implements the IComparable(T)-interface.

public static void ExceptionIfOutOfRange<T>(this T value,
    T lowerBound, T upperBound, string argumentName) where T : IComparable<T>
{
    if (value.CompareTo(lowerBound) < 0 || value.CompareTo(upperBound) > 0)
    {
        throw new ArgumentOutOfRangeException(argumentName);
    }
}

This means that the method will only be shown in the Intellisense on values that it can be applied to:

image

image

Note that in the first case the variable "o" is of the type "object", and the only applicable method is the one that checks for null. In the second case "o" is of the type "int" and now there are two applicable methods, the one that checks if arguments that implements IComparable(T) are within a specified range and the one that checks if an index (int) is within a specified range. Since int is a value type it can't be null so the ExceptionIfNull(T)-method is not applicable, this is little piece of magic is accomplished by the generic constraint "where T : class" that set on the ExceptionIfNull(T)-method.

And here's the code:

#region Using Directives
using System;
using System.Globalization; 
#endregion

namespace Minimal
{
    /// <summary>
    /// Provides helper extension methods for conditional throwing of
    /// exceptions. Mainly used for guarding input parameters.
    /// </summary>
    public static class ThrowHelper
    {
        /// <summary>
        /// Throws an ArgumentNullException if the value is null.
        /// </summary>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="value">The value to check for null.</param>
        /// <param name="argumentName">The name of the argument the value represents.</param>
        /// <exception cref="ArgumentNullException">The value is null.</exception>
        public static void ExceptionIfNull<T>(this T value, string argumentName) where T : class
        {
            if (value == null)
            {
                throw new ArgumentNullException(argumentName);
            }
        }

        /// <summary>
        /// Throws an ArgumentNullException if the value is null.
        /// </summary>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="value">The value to check for null.</param>
        /// <param name="argumentName">The name of the argument the value represents.</param>
        /// <param name="message">A message for the exception.</param>
        /// <exception cref="ArgumentNullException">The value is null.</exception>
        public static void ExceptionIfNull<T>(this T value, string argumentName, string message) where T : class
        {
            if (value == null)
            {
                throw new ArgumentNullException(argumentName, message);
            }
        }

        /// <summary>
        /// Throws an ArgumentNullException if the specified value is null or
        /// throws an ArgumentOutOfRangeException if the specified value is an
        /// empty string.
        /// </summary>
        /// <param name="value">The string to check for null or empty.</param>
        /// <param name="argumentName">The name of the argument the value represents.</param>
        /// <exception cref="ArgumentNullException">The value is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException">The value is an empty string.</exception>
        public static void ExceptionIfNullOrEmpty(this string value,
            string argumentName)
        {
            value.ExceptionIfNull("value");

            if (value.Length == 0)
            {
                throw new ArgumentOutOfRangeException(argumentName,
                    string.Format(CultureInfo.InvariantCulture,
                        "The length of the string '{0}' may not be 0.", argumentName ?? string.Empty));
            }
        }

        /// <summary>
        /// Throws an ArgumentOutOfRangeException if the specified value is not within the range
        /// specified by the lowerBound and upperBound parameters.
        /// </summary>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="value">The value to check that it's not out of range.</param>
        /// <param name="lowerBound">The lowest value that's considered being within the range.</param>
        /// <param name="upperBound">The highest value that's considered being within the range.</param>
        /// <param name="argumentName">The name of the argument the value represents.</param>
        /// <exception cref="ArgumentOutOfRangeException">The value is not within the given range.</exception>
        public static void ExceptionIfOutOfRange<T>(this T value,
            T lowerBound, T upperBound, string argumentName) where T : IComparable<T>
        {
            if (value.CompareTo(lowerBound) < 0 || value.CompareTo(upperBound) > 0)
            {
                throw new ArgumentOutOfRangeException(argumentName);
            }
        }


        /// <summary>
        /// Throws an ArgumentOutOfRangeException if the specified value is not within the range
        /// specified by the lowerBound and upperBound parameters.
        /// </summary>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="value">The value to check that it's not out of range.</param>
        /// <param name="lowerBound">The lowest value that's considered being within the range.</param>
        /// <param name="upperBound">The highest value that's considered being within the range.</param>
        /// <param name="argumentName">The name of the argument the value represents.</param>
        /// <param name="message">A message for the exception.</param>
        /// <exception cref="ArgumentOutOfRangeException">The value is not within the given range.</exception>
        public static void ExceptionIfOutOfRange<T>(this T value,
            T lowerBound, T upperBound, string argumentName, string message) where T : IComparable<T>
        {
            if (value.CompareTo(lowerBound) < 0 || value.CompareTo(upperBound) > 0)
            {
                throw new ArgumentOutOfRangeException(argumentName, message);
            }
        }

        /// <summary>
        /// Throws an IndexOutOfRangeException if the specified index is not within the range
        /// specified by the lowerBound and upperBound parameters.
        /// </summary>
        /// <param name="index">The index to check that it's not out of range.</param>
        /// <param name="lowerBound">The lowest value considered being within the range.</param>
        /// <param name="upperBound">The highest value considered being within the range.</param>
        /// <param name="argumentName">The name of the argument the value represents.</param>
        /// <exception cref="IndexOutOfRangeException">The index is not within the given range.</exception>
        public static void ExceptionIfIndexOutOfRange(this int index,
            int lowerBound, int upperBound, string argumentName)
        {
            if (index < lowerBound || index > upperBound)
            {
                throw new IndexOutOfRangeException();
            }
        }

        /// <summary>
        /// Throws an IndexOutOfRangeException if the specified index is not within the range
        /// specified by the lowerBound and upperBound parameters.
        /// </summary>
        /// <param name="index">The index to check that it's not out of range.</param>
        /// <param name="lowerBound">The lowest value considered being within the range.</param>
        /// <param name="upperBound">The highest value considered being within the range.</param>
        /// <param name="argumentName">The name of the argument the value represents.</param>
        /// <exception cref="IndexOutOfRangeException">The index is not within the given range.</exception>
        public static void ExceptionIfIndexOutOfRange(this long index,
            long lowerBound, long upperBound, string argumentName)
        {
            if (index < lowerBound || index > upperBound)
            {
                throw new IndexOutOfRangeException();
            }
        }
    }
}

Tuesday, February 12, 2008

Exposing collections

Keyvan Nayyeri has a blog post about exposing generic collections rather than lists in API's.

The basis of his post is that he says that it's a bad idea to expose List<T> publicly, I couldn't agree more. Actually I think it's such a bad idea that I didn't realize that it was a wide spread habit. If you're going to expose a collection it should be exposed in one of two ways in my opinion.

  1. The best alternative in most cases is a strongly typed collection named after what it contains (for example StudentCollection contains Student-objects), that implements at least the IEnumerable<Student> or more specific interfaces (ICollection<Student> or IList<Student>) if so needed.
  2. Expose the collections interface, not the implementation and don't specialize the interface more than needed. If the api just exposes a collection of students in no particular order and it should be read only expose it as an IEnumerable<Student>, not ICollection<Student> or IList<Student>.

Also when you take collections as parameters in your methods use the strongly typed collection or interfaces.

EDIT: I've found that there is actually a generic counterpart of the System.Collections.CollectionBase-class, which can be found in the namespace System.Collections.ObjectModel and it's simply called Collection<T>. This saves us the labor of having to implement our own such base class but the principles in this article still holds true.

Before generics were introduced in .net the simplest way to implement a strongly typed collection was to inherit from the System.Collections.CollectionBase-class, for some reason there is no generic version of this class so I've created one of my own (that implements bot the ICollection<T> and the ICollection interfaces). The nice thing about this abstract class is that it uses explicit interface implementation so none of the interface-methods are exposed (if the collection is not cast to the interface) this allows the developer to expose only the wanted methods through the API. The benefit of this is a much clearer API that is a lot easier to use with Intellisense since only the defined methods are shown.

For example to implement a FooCollection you'd inherit from the CollectionBase<T> class as follows:

public class Foo
{

}

public class FooCollection
    : CollectionBase<Foo>
{
    public void Add(Foo item)
    {
        this.InnerCollection.Add(item);
    }

    protected override ICollection<Foo> CreateInnerCollection()
    {
        return new List<Foo>();
    }
}

In this way we have created a strongly typed collection that also implements both the ICollection<Foo> and the non generic ICollection interfaces we also only expose the Add-method keeping the intellisense simple and public API simple (of course all interface methods are implemented and accessible through a cast).

My implementation of CollectionBase<T> is shown below.

/// <summary>
/// An abstract base class used to create strongly typed collections.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
public abstract class CollectionBase<T> :
    ICollection<T>, ICollection
{
    #region Constructor
    /// <summary>
    /// Creates a new instance.
    /// </summary>
    protected CollectionBase()
    {            
        this.InnerCollection = this.CreateInnerCollection();
    }

    /// <summary>
    /// Creates a new instance and sets the inner collection to the supplied
    /// collection.
    /// </summary>
    /// <param name="innerCollection">The collection to use to store
    /// the items internally.</param>
    /// <exception cref="ArgumentNullException">Thrown if the innerCollection parameter
    /// is null (Nothing in VB).</exception>
    protected CollectionBase(ICollection<T> innerCollection)
    {
        if (innerCollection == null)
            throw new ArgumentNullException("innerCollection");

        this.InnerCollection = innerCollection;
    }
    #endregion

    #region Properties
    #region InnerCollection
    [DebuggerBrowsable(DebuggerBrowsableState.Never), EditorBrowsable(EditorBrowsableState.Never)]
    private ICollection<T> _innerCollection;

    /// <summary>
    /// A collection that stores the items internally.
    /// </summary>
    protected ICollection<T> InnerCollection
    {
        [DebuggerStepThrough]
        get { return _innerCollection; }
        [DebuggerStepThrough]
        set { _innerCollection = value; }
    }
    #endregion InnerCollection
    #endregion

    #region Methods
    #region CreateInnerCollection
    /// <summary>
    /// When implemented by a sub class this method creates a collection
    /// that can be used as inner collection.
    /// </summary>
    /// <returns>A new ICollecion instance.</returns>
    protected abstract ICollection<T> CreateInnerCollection(); 
    #endregion CreateInnerCollection
    #endregion Methods

    #region ICollection<T> Members

    void ICollection<T>.Add(T item)
    {
        this.InnerCollection.Add(item);
    }

    void ICollection<T>.Clear()
    {
        this.InnerCollection.Clear();
    }

    bool ICollection<T>.Contains(T item)
    {
        return this.InnerCollection.Contains(item);
    }

    void ICollection<T>.CopyTo(T[] array, int arrayIndex)
    {
        this.InnerCollection.CopyTo(array, arrayIndex);
    }

    /// <summary>
    /// Gets the number of items in the collection.
    /// </summary>
    public int Count
    {
        get { return this.InnerCollection.Count; }
    }

    bool ICollection<T>.IsReadOnly
    {
        get { return this.InnerCollection.IsReadOnly; }
    }

    bool ICollection<T>.Remove(T item)
    {
        return this.InnerCollection.Remove(item);
    }

    #endregion

    #region IEnumerable<T> Members

    public IEnumerator<T> GetEnumerator()
    {
        return this.InnerCollection.GetEnumerator();
    }

    #endregion

    #region IEnumerable Members

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.InnerCollection.GetEnumerator();
    }

    #endregion

    #region ICollection Members

    void ICollection.CopyTo(Array array, int index)
    {
        this.InnerCollection.CopyTo((T[])array, index);
    }

    int ICollection.Count
    {
        get { return this.InnerCollection.Count; }
    }

    bool ICollection.IsSynchronized
    {
        get { return false; }
    }

    object ICollection.SyncRoot
    {
        get { return this.InnerCollection; }
    }

    #endregion
}

 

Technorati-taggar: ,,