Friday, July 8, 2011

Pet Peeve: Misuse of KeyValuePair

This is one that irks me when I come across it.

public IList<KeyValuePair<bool, string>> ProcessRecords(IList<MyRecord> records)
{
    var results = new List<KeyValuePair<bool, string>>();
    foreach( var record in records)
    {
         // Do some processing...
         if (success)
             results.Add(new KeyValuePair<bool, string>(true, "Message indicating record was processed successfully.");
        else
            results.Add(new KeyValuePair<bool, string>(false, "Message indicating record was not processed successfully.");
    }
    return results;
}

The above is just a pseudo-example similar to some situations I've come across and even some examples on the web on how you can use KeyValuePair, and even one that gave an example of a KeyValuePair of KeyValuePairs to return a bastardization of triplets. *shudder* The alternative to KeyValuePair would be to create a new class which by all rights would be identical to KeyValuePair. So why not just use KeyValuePair?

Because it is misleading, and it's no different to writing a class to represent a tax invoice and naming it "Order", or "Thing" for that matter. KeyValuePair is meant to store a Key, as in a unique value, against a value. If your method is designed to return a unique list of keys with respective values then by all means use KeyValuePair. But if you're using it to return arbitrary pairs of values then for clairity just create a Pair class instead. 

The problem with returning KeyValuePairs is that looking at that return type you would expect that the data would be suited to being placed in a Dictionary. However if you're returning arbitrary pairs of values then you are misleading other developers all for the sake of being too lazy to define a simple generic class.