Use extension methods to keep your code simple and DRY

In this article I’ll show you why and how to use generic extension methods to keep your code simple and DRY.

Table of contents

The Problem

Consider this simple model:

public class Format
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}   
    
public class Product 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public IEnumerable<Category> Categories { get; set; }
    public IEnumerable<Format> Formats { get; set; }

    public bool HasCategories
    {
        get
        {
            if(Categories == null)
                return false;

            return Categories.Any();
        }
    }

    public bool HasFormats
    {
        get
        {
            if(Formats == null)
                return false;

            return Formats.Any();
        }
    }
}

As you can see, I have created to properties HasCategories and HasFormats in the Product class to check if the collections Categories and Formats have any element, respectively.
The following ASP.NET MVC view shows how these properties can be used:

@model Product

<h1>@Model.Name</h1>

<p>@Html.DisplayFor(model => model.Description)</p>

<h2>Product Categories</h2>

<ul>
@if(Model.HasCategories)
    {
        foreach(var category in Model.Categories)
        {
        <li>@category.Name</li>
        }
    }
    else
    {
        <li>This product has no categories</li>
    }
</ul>

<h2>Formats Available</h2>
<ul>
@if(Model.HasFormats)
    {
        foreach(var format in Model.Formats)
        {
        <li>@format.Name</li>
        }
    }
    else
    {
        <li>No formats available</li>
    }
</ul>

There is a problem with this code though – the properties improve the code readability and can be reused, but you may have dozens or hundreds of classes that may need properties like these. It is a verious tedious and time consuming task to create such properties in all the classes we need – a better option would be to create an extension method to do that work for us.

Extension methods to the rescue

If you take a good look into the HasCategories and HasFormats properties you can see that the code is similar, the only thing that changes is the type of the properties.

We can then create a generic extension method to check if any object that implements IEnumerable (List, etc) is null or empty:

namespace Extensions
{
    public static class IEnumerableExtensions
    {
        /// <summary>
        /// Determines whether an enumerable is null or empty.
        /// </summary>
        /// <typeparam name="T">Type of the enumerable</typeparam>
        /// <param name="collection">The collection.</param>
        /// <returns>
        ///   <c>true</c> if the enumerable is null or empty; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
        {
            if(collection == null)
                return true;

            return !collection.Any();
        }
    }
}

There’s no more need to have the properties HasCategories and HasFormats so they can be removed from the Product class. The code now looks simpler and cleaner:

public class Product 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public IEnumerable<Category> Categories { get; set; }
    public IEnumerable<Format> Formats { get; set; }
}

Finally, we can change the ASP.NET MVC view to use the extension method:

@using Extensions
@model Product

<h1>@Model.Name</h1>
<p>@Html.DisplayFor(model => model.Description)</p>

<h2>Product Categories</h2>
<ul>
@if(Model.Categories.IsNullOrEmpty())
{
    foreach(var category in Model.Categories)
    {
    <li>@category.Name</li>
    }
}
else
{
    <li>This product has no categories</li>
}
</ul>

<h2>Formats Available</h2>
<ul>
@if(Model.Formats.IsNullOrEmpty())
{
    foreach(var format in Model.Formats)
    {
    <li>@format.Name</li>
    }
}
else
{
    <li>No formats available</li>
}
</ul>

Final thoughts

In short, you can (and should) use extension methods to keep your code DRY.

Basically you need to identity pieces of code that are generic enough and replace them with an extension method, if possible. You will have code that is easier to maintain and also more time to develop other funcionalities.

References

Advertisements