Updating an item in a list without a reference with lambdas

15 Feb

I have to confess I am enjoying lambdas a bit much. I am making this post to show a cool way of avoiding code loops (there are still loops in CLR of course).

private void UpdatePerson(Person updatedPersonObject)
{
    var outOfDatePerson = _people
            .First(person => person.Id == updatedPersonObject.Id);
    int index = _people.IndexOf(outOfDatePersonObject);
    _people[index] = updatedPersonObject;
}

private void UpdatePerson_OldCSharp(Person updatedPersonObject)
{
    int outOfDatePersonIndex = 0;
    for (int i = 0; i < _people.Count ; i++ )
    {
        if (_people[i].Id == updatedPersonObject.Id)
        {
            outOfDatePersonIndex = i;
            break;
        }
    }
    _people[outOfDatePersonIndex] = updatedPersonObject;
}

From the two code samples it is worth noticing the difference in the number of lines and in the hierarchical nature of the code. The traditional C# for loop approach (the second method) leads me to cringe from a maintenance point of view. Each line of code is highly contextual and relies heavily on multiple levels of language constructs.

The first method (the lambda way) to me is much more readable and also maintainable. There is a flat hierarchy which is much easier to read as it doesn’t involve following the loop through code. I argue it is easier to maintain as the lines can change order more and will still be doing the same thing. It is also easier to update as there is less code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: