OdeToCode IC Logo

What’s Wrong With This Code (#23)

Sunday, October 18, 2009

Keith Dahlby started a discussion with his post “Is Functional Abstraction Too Clever?” Read Keith’s post for the background, but I would agree with all the comments I’ve read so far and I say the functional approach is a good solution to the problem.

Keith’s post did get me thinking of things that could go wrong in the hands of a developer who doesn’t understand how in-memory LINQ is working.

As an example, let’s use Keith’s Values extension method …

public static IEnumerable<int> Values(
    this Random random, 
    int minValue, int maxValue)
{
    while (true)
        yield return random.Next(minValue, maxValue);
}

… and let’s say a developer is using the above to satisfy the following requirements.

  1. Give me an array of 10 random numbers between 1 and 100
  2. The 10 numbers should be unique
  3. The 10 numbers should be appear in order from lowest value to highest value

What’s wrong with the following code?

var values =
    new Random().Values(1, 100)
                .Distinct()
                .OrderBy(value => value)
                .Take(10)
                .ToArray();

Do you think it’s a subtle problem?

What’s an easy fix?