A couple of weeks ago at the Wellington .NET User Group we had a very interesting presentation from Patrick, one of the fine TradeMe developers, talking about the use of simple “value objects” to represent distinct kinds of information.

This presentation came to mind today, when I caught myself passing folder paths around some code as strings instead of using DirectoryInfo instances. Converting the code to use DirectoryInfo values instead of the strings not only made the code simpler and easier to read, it highlighted a couple of bugs well before I had a chance to test the code in question.

Even better, I found a couple of places were a simple extension method could make the code even simpler, allowing me to adopt a more declarative style (for a couple of lines at least).

For example, the FolderForEnvironment method returns the location in which data files for a particular environment should be saved for later processing. The EnsureExists() method will automatically create the folder if it doesn’t already exist, allowing the rest of the routine to rely on the folders existence.

var referenceFolder = FolderForEnvironment(ReferenceSystem).EnsureExists();
var targetFolder = FolderForEnvironment(TargetSystem).EnsureExists();

Here’s the source for the DirectoryInfoExtensions class.

/// <summary>
/// Extension methods for DirectoryInfo
/// </summary>
public static class DirectoryInfoExtensions
{
    /// <summary>
    /// Enforce the existence of a directory, throwing an exception if it is missing
    /// </summary>
    /// <param name="directory">DirectoryInfo for the directory to test</param>
    /// <returns>Directory parameter, for chaining.</returns>
    /// <exception cref="DirectoryNotFoundException">If the directory is missing</exception>
    public static DirectoryInfo MustExist(this DirectoryInfo directory)
    {
        if (!directory.Exists)
        {
            throw new DirectoryNotFoundException(directory.FullName);
        }

        return directory;
    }

    /// <summary>
    /// Ensure the existence of a directory, creating it if necessary
    /// </summary>
    /// <param name="directory">DirectoryInfo for the directory to test</param>
    /// <returns>Directory parameter, for chaining.</returns>
    public static DirectoryInfo EnsureExists(this DirectoryInfo directory)
    {
        if (!directory.Exists)
        {
            directory.Create();
        }

        return directory;
    }
}

Comments

blog comments powered by Disqus