Register Login

 

Welcome to the Coach Factor blog. Here you will find all of our ideas on software development. Subscribe at  http://blog.nventive.net.

# Tuesday, April 21, 2009

For the last couple of days, Michael, a friend of us has changed his Messenger tagline to: “If the code speaks for itself, don’t interrupt”.

It expresses clearly the intent of Umbrella… To allow the developer to create code that speaks for itself as opposed to code that requires a translator.

Let’s take the following code:

static void Main(string[] args)

{

    foreach (var arg in args)

    {

        if (!string.IsNullOrEmpty(arg))

        {

            Console.WriteLine(arg);

        }

    }

 

    Console.ReadLine();

}

 

If we were to “listen” to the code, it would say that for each arg in the args list, if the string has a value, it should be displayed in the console.

So in order to let the code speak more clearly, we should be able to write something like:

static void Main(string[] args)

{

    args.Where(a => a.HasValue())

        .ForEach(a => Console.WriteLine(a));

 

    Console.ReadLine();

}

 
It might not show as there is not much going on, but the intent is clearer.
 
Even if the following two statements are equivalent, one is more focused and concise:
 

!string.IsNullOrEmpty(arg)

 

arg.HasValue()

 

In order to obtain this simpler syntax, we simply leverage the extension methods paradigm from C# 3.0 and LINQ for the Where clause:

public static class StringExtensions

{

    public static bool HasValue(this string value)

    {

        return !string.IsNullOrEmpty(value);

    }

}

 

Remember, to code an extension it takes 3 ingredients:

  1. A static class
  2. A static method
  3. The this modified on the first method parameter

As you probably guessed, the ForEach implementation is as simple:

public static class EnumerableExtensions

{

    public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)

    {

        foreach (var item in items)

        {

            action(item);

        }

    }

}

 

Two important things to node with the ForEach extension:

  1. We’ve extended the minimal interface required (IEnumerable<T>)
  2. We’ve leveraged the existing Action<T> delegate as opposed to defining a custom one

In the following posts, we’ll show how much more the code can say!

() => “Francois”

Tuesday, April 21, 2009 10:30:26 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
.net - Extension Methods | Umbrella
Search
Archive
<April 2009>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
Statistics
Total Posts: 98
This Year: 28
This Month: 3
This Week: 0
Comments: 17
Sign In