Dictionary Naming Guidelines

Posted: 1/23/2008 4:05:02 PM

Generic dictionaries are a great thing, they let you add and retrieve objects very quickly. My current gig has a lot of need for them because we've got tons of data that needs to be quickly referenced (I'll post more about Dictionary memory performance later). The problem is that developers everywhere like to use very un-descriptive names for their dictionaries, especially nested dictionaries. Usually you'd like to avoid nesting these things, but sometimes you don't have a choice and making a bunch of derived classes adds a lot of code and more "stuff" you have to sift through.

Simple Example:
Dictionary<int, string> _peopleDictionary;
What is the key? Is it a PersonId? Is it a CustomerId? Is it an EmployeeId? Is it a Social Security Number?

What about the value? Is it First Name, Last Name, First then Last, Last then First, Nickname?

In order to find out, a developer who takes over your code has to look up all references to PeopleDictionary and find out what the Key and Values are, yielding a gigantic waste of time. (Worse yet, it could be you looking up all the references because you haven't looked at this particular code in 7 months). And that is even a non-nested dictionary!

Now, can you tell me what kind of data is stored in the below object?
Dictionary<int, Dictionary<int, List<string>>> _customerIdToOrderIdToDescriptions;
Sure the name is a little long, but think about how many different kinds of data are being stored in it. Plus you didn't have to make a custom object for a one-off need. Anyone who has to modify your code can easily use this object without trying to figure out what "OrdersDictionary" is actually storing.

FXCop Guys: I'll give you $10 if you add a rule saying that generic dictionary variable names have to contain the string literal "To".

Of note: it's generally considered bad practice to use nested generics, but if you do, just make sure that you don't expose nested generic types by returning them in public methods or by making a public property with a nested type. Keep them for internal use within your class only.

Tags: Tips and Tricks;Wishlist