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.

# 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
# Sunday, April 19, 2009

In an agile team, things go fast. And when things go fast, it usually gets messy. But then, why agile teams have proven record of success?

An agile method is based on a set of values and principles that embrace and  support each other. When one aspect of the philosophy looks like it’s not “formal” enough, another practice supports its weaknesses.

Environment

In order to stay focused on the task at hand, an agile team will have to setup its environment to make sure everything runs smoothly. They will create unit tests and make sure they get the green light prior to a check-in; but that’s usually not enough. They need to make sure it works on their machine and that it can work on any other box matching the requirements.Those requirements represent the environment the software needs to live in to run smoothly (or at all). It will vary but can usually include:

  • A specific version of the runtime
  • Third party assemblies deployed (locally or in the gac)
  • Configuration files at different URIs (ideally relative)
  • Environment variables
  • WMI schema registered
  • Registry entries

Continuous Integration

An many variables come into play, we need to make sure that for a given set of values, the software always works the same. In order to do so, agile teams will setup a clean environment (build server), seal it and automatically test that whatever changes in the software, it will continue to run on this environment. That’s what continuous integration (CI) is all about: continuously integrating the latest changes into a given environment and automatically checking that it installs correctly, that it runs as expected.

Contamination

Why isn’t the dev environment clean enough? Because we all know many things are going on and aren’t ideal on a dev box:

  • A newer version of a component is installed to test out features we might need in the future
  • A beta is installed and then uninstalled (partially)
  • Registry entries get deleted or manually added
  • Parallel versions are running
  • Debug versions are running
  • Bits exist locally but aren’t in sync with source control (think Lib folder)

Those are all reasons why it might “work on your machine” but not on “every machine”. Choose your side.

Long and External

When code changes, it might break existing assumption. Agile teams will try to document those assumptions in some executable format, usually unit tests. But not all tests are born equal. Some are bigger and broader that simple units. Some are testing the integration, the system and the use case as a whole. Should a developer wait for every single test to pass when he changes a string.Format() argument before he commits the change back to the repository? Ideally yes. But that’s not ideal; he might end up having to wait for a while for those exhaustive tests to pass (or will they?).

When you have a CI mechanism with a dedicated build machine; the whole suite of tests will automatically run in the background when something changes in the source code repository. While the developer continue working on new problems, he will get notified if something broke the build. The context the breaking change was made in has still not totally dissipated and it is easy to figure out what went wrong.

A long running test is one thing, but what about external tests? Some other teams might have some dependencies on your code. Some other projects of your own might have some dependencies on these modified bits? What then? Well they should also be part of the CI build so that they too can receive quick feedback that something is going wrong.

Tools

There are many tools to help you with CI. Cruise Control .net is one of the most popular. CI factory is a facade over CC.net that eases the configuration process.

Process

CI should be put in place as soon as possible; usually during Sprint 0 so that the team is up and running for Sprint 1 and leverage the short feedback loop quickly. A good enough CI environment can usually be setup in less than a day.

But what if it fails? What if it fails between the new tests have been committed and they don’t make sense? What if code shows a flaw in the acceptance criteria? What if you have a dedicated test team as opposed to a truly cross-functional dev team? That’s where things get interesting.

There’s no absolute truth to this one. However, depending on the type of test that failed (integrated or unit), it might end up being the dedicated test team that lives on the front line, assesses the bug and then informs the dev team that something went wrong.

() => “Francois”

Sunday, April 19, 2009 3:26:00 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
.net | Agile - Development

Grigori, Program Manager of Enterprise Library at Microsoft Patterns & Practices has published the prioritized backlog for V5. He explains in details the procedure that has taken place to select items we’ll be working on. It is impressive how Microsoft has turned to the community to get feedback: blog posts, advisory board, events, Codeplex, MSDN, …

It also exciting to see how many of you answered the survey. It shows that Enterprise Library provides great value to many of us and that we should continue working with this interesting beast.

If you have a look at the backlog, you’ll see that we’ll spend much time trying to simplify the EntLib story. Whether it’s through Architecture refactoring, documentation, labs, the story should become clearer to understand and easier to tell. It will also likely embrace new technologies like WPF and WCF.

Go have a look! With previous versions, there was a weekly drop on Codeplex. You should get some bits of V5 sooner than later as we’ve already started an iteration!

() => “Francois”

Sunday, April 19, 2009 12:08:35 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
.net - Microsoft PnP
Search
Archive
<April 2009>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
Statistics
Total Posts: 98
This Year: 28
This Month: 1
This Week: 1
Comments: 17
Sign In