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)
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:
- A static class
- A static method
- 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:
- We’ve extended the minimal interface required (IEnumerable<T>)
- 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”