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.

# Sunday, April 26, 2009

More fun with dictionaries on the way. We’ve seen how to read from a dictionary with the GetValueOrDefault() extension method but that’s not enough.

We usually need a way to add items to a dictionary if they aren’t already there. Here’s a simple example of a caching mechanism that relies on in-memory dictionaries:

Given:

public interface IOrderRepository

{

    Order GetOrderById(int id);

}

 

public class Order

{

    public int Id { get; set; }

}

 

A simple caching mechanism can be obtained using the Decorator pattern:

public class CacheOrderRepository : IOrderRepository

{

    private Dictionary<int, Order> orders = new Dictionary<int, Order>();

 

    public CacheOrderRepository(IOrderRepository repository)

    {

        Repository = repository;

    }

 

    public IOrderRepository Repository

    {

        get;

        private set;

    }

 

    #region IOrderRepository Members

 

    public Order GetOrderById(int id)

    {

        Order order;

 

        if (!orders.TryGetValue(id, out order))

        {

            order = Repository.GetOrderById(id);

            orders.Add(id, order);

        }

 

        return order;

    }

 

    #endregion

}

 

What basically happens here is that we’ll first try to find the value from the local dictionary (hence the cache) and if not present, go to the real repository to fetch the value and then create an entry in the local cache with the result. So what the code really wants to say is:

public Order GetOrderById(int id)

{

    return orders.FindOrCreate(id, () => Repository.GetOrderById(id));

}

 

A simple refactoring of the previous implementation into an extension method would lead to something like:

 

public static class DictionaryExtensions

{

    public static TValue FindOrCreate<TKey, TValue>(

        this IDictionary<TKey, TValue> items, TKey key,

        Func<TValue> factory)

    {

        TValue value;

 

        if (!items.TryGetValue(key, out value))

        {

            value = factory();

            items.Add(key, value);

        }

 

        return value;

    }

}

 

Note again that we’re extending the minimal interface, IDictionary<T>, and leveraging an existing delegate type, Func<T>.

() => “Francois”

Sunday, April 26, 2009 6:28:29 PM (Eastern Standard Time, UTC-05:00)  #    Comments [2] -
.net - Extension Methods | Umbrella
# Friday, April 24, 2009

So far, we’ve seen useful tricks to extend basic collection types like IEnumerable<T> and ICollection<T> but more complex collections deserve attention too!

 

Let’s look at IDictionary<T>. Here’s some code I stumbled upon recently; it is a partial implementation of IDataErrorInfo:

 

public class Order : IDataErrorInfo

{

    private IDictionary<string, string> errors =

        new Dictionary<string, string>();

 

    private decimal amount;

 

    public decimal Amount

    {

        get { return amount; }

        set

        {

            amount = value;

 

            if (amount <= 0)

            {

                errors["Amount"] = "Amount has to be larger than 0";

            }

            else

            {

                errors.Remove("Amount");

            }

        }

    }

 

    #region IDataErrorInfo Members

 

    public string Error

    {

        get { return null; }

    }

 

    public string this[string columnName]

    {

        get

        {

            if (errors.ContainsKey(columnName))

            {

                return errors[columnName];

            }

            else

            {

                return null;

            }

        }

    }

 

    #endregion

}

 

The interesting part is:

if (errors.ContainsKey(columnName))

{

    return errors[columnName];

}

else

{

    return null;

}

 

What’s the intent of this code? Pretty obvious isn’t it? It checks whether the dictionary has a value for a given key, then returns the value. If the key isn’t found, it returns the default value. This is similar to how the Nullable<T> type works:

int? index = null;

 

int indexValue = index.GetValueOrDefault();

 

Here, for obvious reasons, indexValue’s value will equal 0. But what’s interesting is the GetValueOrDefault() method. It clearly expresses the intent as opposed to:

int indexValue = index == null ? 0 : index.Value;

 

The same thing could apply to dictionaries but hasn’t been provided as part of the Base Class Library:

public string this[string columnName]

{

    get { return errors.GetValueOrDefault(columnName); }

}

 

Here’s Umbrella’s implementation:

public static class DictionaryExtensions

{

    public static TValue GetValueOrDefault<TKey, TValue>(

        this IDictionary<TKey, TValue> dictionary,

        TKey key)

    {

        return GetValueOrDefault(dictionary, key, default(TValue));

    }

 

    public static TValue GetValueOrDefault<TKey, TValue>(

        this IDictionary<TKey, TValue> dictionary,

        TKey key,

        TValue defaultValue)

    {

        return GetValueOrDefault(dictionary, key, () => defaultValue);

    }

 

    public static TValue GetValueOrDefault<TKey, TValue>(

        this IDictionary<TKey, TValue> dictionary,

        TKey key,

        Func<TValue> defaultValueProvider)

    {

        TValue value;

 

        if (!dictionary.TryGetValue(key, out value))

        {

            value = defaultValueProvider();

        }

 

        return value;

    }

}

 

The first method is an overload that will return default(T) if a default value is required.

The second method takes the defaultValue as a parameter

The third method contains the actual implementation and relies on a delegate to obtain the value since the defaultValue could either take some time to process or cannot be known in advance.

Again, these extension methods are small helpers to reduce the friction of th BCL. They are not meant to completely change the programming paradigm. They aren’t intrusive either. They should increase predictability of the source code with a side effect of decreasing the total lines of code count.

() => “Francois”

Friday, April 24, 2009 7:23:50 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
.net - Extension Methods | Umbrella
# Thursday, April 23, 2009

There is code what we type over and over again without realizing how many mistakes can be made in a few lines. Let’s take the example where we want to remove items from a collection. Intuitively, the code should be something like:

var orders = new List<Order> {

    new Order { Total = 100 },

    new Order { Total = 150 },

    new Order { Total = 200 }};

 

foreach (var order in orders)

{

    if (order.Total > 100)

    {

        orders.Remove(order);

    }

}

 

However, this will fail miserably with an “InvalidOperationException: Collection was modified; enumeration operation may not execute.”

In fact, it doesn’t fail on the Remove() call, it fails on the MoveNext() as we can’t enumerate a modified collection or can’t modify a collection while enumerating. In order to work correctly, we learned that we need to first keep track of the items to remove and then enumerate through those and remove them from the collection:

var orders = new List<Order> {

    new Order { Total = 100 },

    new Order { Total = 150 },

    new Order { Total = 200 }};

 

var ordersToRemove = new List<Order>();

 

foreach (var order in orders)

{

    if (order.Total > 100)

    {

        ordersToRemove.Add(order);

    }

}

 

foreach (var order in ordersToRemove)

{

    orders.Remove(order);

}

 

Wow! That is a huge amount of code. At least it can be refactored in a generic extension method:

public static class CollectionExtensions

{

    public static void Remove<T>(

        this ICollection<T> collection,

        Func<T, bool> predicate)

    {

        var itemsToRemove = new List<T>();

 

        foreach (var item in collection)

        {

            if (predicate(item))

            {

                itemsToRemove.Add(item);

            }

        }

 

        foreach (var item in itemsToRemove)

        {

            collection.Remove(item);

        }

    }

}

 

And then be used as:

orders.Remove(o => o.Total > 100);

 

In Umbrella, we go the extra mile and “simplify” the implementation of the Remove() extension method and dog food our own extensions:

public static void Remove<T>(

    this ICollection<T> collection,

    Func<T, bool> predicate)

{

    collection

        .Where(predicate)

        .ToList()

        .ForEach(item => collection.Remove(item));

}

 

What basically happens here is that we:

  1. Filter the original collection to keep only the items to remove (Sounds familiar?)
  2. Copy those items to a temporary list (Remember?)
  3. For each of those items, call Remove() on the original collection (Rings a bell?)

() => “Francois”

Thursday, April 23, 2009 9:03:24 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
.net - Extension Methods | Umbrella
# Wednesday, April 22, 2009

Some extension methods in Umbrella are simple but yet useful. It usually ends up being exiting methods from the Base Class Library that weren’t defined on the simplest interface required but more as a helper method on more concrete types:

Let’s start with the most straighforward example:

Given:

public class Order

{

    public decimal Total { get; set; }

}

 

We’ll usually see something like:

var orders = new List<Order>();

 

var order = new Order();

orders.Add(order);

 

But when the item to add to the collection has a default constructor, we could have a shorter syntax:

var orders = new List<Order>();

 

var order = orders.AddNew();

But AddNew() isn’t a member of List<T>. Have you guessed how AddNew() is implemented? Using extension methods, of course but what should be extended? List<T>? It is actually ICollection<T> as it is the interface containing the Add method.

public static class CollectionExtensions

{

    public static T AddNew<T>(this ICollection<T> items)

        where T : new()

    {

        T item = new T();

 

        items.Add(item);

 

        return item;

    }

}

 

A generic constraint on T having a default constructor is required so that new() can be called.

I mentioned that some helper methods have been defined on concrete types on the past where now, with extension methods, they could be extending simple interfaces. It is the case of List<T>.AddRange():

var orders = new List<Order>();

 

var newOrders = new List<Order> {

    new Order { Total = 100 },

    new Order { Total = 150 },

    new Order { Total = 200 }};

 

orders.AddRange(newOrders);

 

What AddRange logically does, is call Add for each new item. If we were to boil it down to its simplest form:

public static class CollectionExtensions

{

    public static void AddRange<T>(

      this ICollection<T> collection,

      IEnumerable<T> items)

    {

        items.ForEach(collection.Add);

    }

}

 

Don’t get confused by the “collection.Add” syntax, it is the method group syntax. The equivalent lambda expression would be:

items.ForEach(item => collection.Add(item));

 

That’s it for Part 2!

() => “Francois”

Wednesday, April 22, 2009 11:19:16 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net - Extension Methods | Umbrella
# 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
# Monday, April 20, 2009

Everything is about perception. When people look at Umbrella, they think it is huge; for us, it is simply a thin layer over the BCL and various MS technologies that improve the development experience.

Design principles for Umbrella are really simple:

  • Eat our own dog food
    • Umbrella has been developed using Umbrella.
  • Don’t repeat yourself
    • It’s really about addressing an issue once and only once.
  • Stronger abstractions
    • Coming up with the ISource<T> name for a generic getter-setter allows us to create higher abstraction.
  • Fluent interface
    • name.Validation().NotNull() as opposed to ArgumentHelper.CheckNotNull(name)
  • Predictability
    • The members are where they feel natural and discoverability is easy.
  • Zero friction
    • Supported by other principles, it is mainly focused as working effectively in a TDD environment, easily mockable, extensible, …
  • Leverage and Reuse
    • We use Action<T> and Func<T> as opposed to defining new delegates over and over again

In order to make this happen, we heavily rely on new C# 3.0 language features like lambda expressions and extension methods.

In order to showcase many of the functionalities we use on a daily basis, we’re launching a new serie of blog posts focused specifically at Umbrella. Stay tuned!

() => “Francois”

Monday, April 20, 2009 1:57:05 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
Umbrella
# Wednesday, April 01, 2009

As you know, nVentive's founders Erik Renaud and Francois Tanguay are both MVPs. Now that means that we get an opportunity to work with Microsoft in order to provide feedback from our clients and the community. Now if you'd like to read more on what it means to Erik, go ahead and read it here !

 

Wednesday, April 01, 2009 4:27:05 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
.net | Umbrella
# Thursday, September 25, 2008

nVentive will be presenting it's "Top 10 Umbrellas" talk at the Ottawa.NET Community on Thursday, November 5th. Come and hear us talk about Umbrella and how the ideas within can save you development time.

Thursday, September 25, 2008 12:02:22 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net | Announcement | Umbrella
# Thursday, September 11, 2008

For the second time this year, nVentive will be presenting at DevTeach, happening in our home town of Montreal from December 1st to the 5th. Come and catch us talk about agility in our "Done Done" conversation, or about hard core programming in our "Top 10 Umbrellas" talk.

Thursday, September 11, 2008 2:05:35 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Announcement | Umbrella
# Friday, August 29, 2008

We've been looking at tools lately that could an agile team get a better view of the quality of the software they are writing. On of those is NDepend, a tool that will inspect your assemblies, determine your code's dependencies and then calculate some metrics for you to analyze. The output will typically be a report, in HTML format. Since this step can be automated, We strongly suggest that you put this into your continuous integration process because from that point, you'll be able see the metrics for your software change with time.

On a previous project, we had integrated NDepend on the daily build and at the of each iteration, we would take a few minutes to look at the reports and note a few actions to be taken during the next one. It was a great way to maintain quality and I strongly recommend you integrate it on your next project.

Now where this tool really shines, is with the VisualNDepend application. This one allows you to visualize the metrics of your software, query your software's compiled code through a SQL like language, and perform comparisons between 2 different reports.

Here are a few examples of the queries you can do in CQL:

SELECT TOP 10 METHODS WHERE CouldBePrivate

SELECT TOP 10 FIELDS WHERE CouldBePrivate

SELECT TOP 10 TYPES WHERE IsClass AND NbChildren ==0 AND !IsSealed AND !IsStatic ORDER BY NbLinesOfCode

Here are a few snapshots of the tool when run on our own Umbrella library.

Picture 1

This image shows Umbrella being analyzed, with the mouse pointer on one method called "Truncate". NDepend shows metrics and information all on one easy screen.

Picture 2

This image shows the result of the execution of 1 CQL query and where in the assembly (in blue) are located the results. Once again, bravo for NDepend: quick, concise and visual.

The author of the product Patrick Smacchia gave an interview to the Visual Studio Talk Show, a french PodCast from Montreal; if you can, we strongly suggest you listen to it and hear what the author himself has to say about this great product.

Thursday, August 28, 2008 11:50:42 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Architecture | Process | Umbrella
# Monday, August 25, 2008

The Montreal .NET Community (formelly the GUVSM) has redone itself.

There is a new name and a new website in order to reflect the common interests that the community has in .net related technologies. There will be special interests groups for .Net, Team SystemSql and architecture. What's new though is that Francois and I will be pushing a new concept in the .net group called @Lunch.

@Lunch is basically an open session, once a month, where a subject will examined in a more informal way. It is modeled on the way Alt.NET and opens spaces work and will surely provoke a few interesting discussions. One of the things we will promote is to determine the subject of the next meeting, during the last few minutes of the meeting occuring. What an "Agile" way of learning what's most important. The first @Lunch is scheduled for September 24th and will be moderated by Francois, speaking on extension methods.

I suggest you visit the calendar, and find which sessions interest you the most. You can even subscribe to the calendar through a RSS feed; what a nice touch !

The last thing for this post is an upcoming Umbrella talk; we will be presenting our session called "Top 10 Umbrellas" at the .Net group of the Montreal .Net Community on October 20th. If you're interested in what it is, or how it can help you, we suggest you come by and listen what we have to say.

Monday, August 25, 2008 2:01:02 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net | Announcement | Umbrella
# Tuesday, May 20, 2008

Amazing how he got it right.

This guy is busy like 10 of us and still, he's able to appreciate a piece of code I wouldn't dare taking less than 2 hours explaining the value of.

Here's what he had to say about Umbrella:

It is exceedingly broad and includes literally hundreds of new methods and helpers. However, I don't think you're expected to "learn" Umbrella as they hope you'll stumble into it...in a good way. It's like the concept of The Pit of Success. There's little easier than just falling, and the idea is that if you've designed an API correctly folks will just fall into success.

This should probably go on our home page as the project description.

Thanks Scott!

Tuesday, May 20, 2008 8:26:13 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Umbrella
# Tuesday, May 13, 2008

Umbrella is nVentive's attempt at filling the gaps in the existing .net framework and related technologies; hence reducing friction and increasing the predictability of the api.

It consists of a set of helpers and additional abstractions that will likely augment one's vocabulary and level of abstraction. This is the first drop of the framework, and we look forward to adding new modules, that will complement Unity, Enterprise Library, Entity Framework and more.

Go check it out on CodePlex (www.codeplex.com/Umbrella) and see how you can diminish your software's complexity by using new patterns.

Tuesday, May 13, 2008 8:28:02 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Announcement | Umbrella
Search
Archive
<July 2010>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567
Statistics
Total Posts: 98
This Year: 28
This Month: 3
This Week: 0
Comments: 17
Sign In