Naming Things is Hard: Dictionaries

Following on from my previous post on naming things, here's a few words about naming dictionaries.

I've been working with a codebase recently which makes a lot of use of dictionaries, and myself often find them useful when implementing a kind of strategy pattern where the keys are values you might otherwise have in a switch statement, something like this:

public class Foo
    private readonly Dictionary<CustomerType, Action<Customer>> _customerActionsByType;

    public Foo()
        _customerActionsByType = new Dictionary<CustomerType, Action<Customer>>
            { CustomerType.Anonymous, DoAnonymousCustomerStuff },
            { CustomerType.Registered, DoRegisteredCustomerStuff }

    public void DoCustomerStuff(Customer customer)

    private static void DoAnonymousCustomerStuff(Customer customer)

    private static void DoRegisteredCustomerStuff(Customer customer)

Through working with lots of dictionaries, I've started naming them as in the example above - [value type]By[key type]. So, for other, possibly-gratuitous examples:

  • sectionsById
  • eventsByDayOfTheWeek
  • ordersByCustomer

…you get the idea. I like this naming pattern for dictionaries because it includes both the things the dictionary structure exposes to the program - the types of the keys and the values - in a way which also describes the purpose of the object. It doesn't contain the word 'dictionary' because that's an implementation detail.

Print | posted @ Tuesday, December 30, 2014 8:54 AM

Comments on this entry:

Gravatar # re: Naming Things is Hard: Dictionaries
by Heath at 1/4/2015 5:58 AM

I tend to use a lot of dictionaries, and you are right. Naming them can be difficult. I like your convention, makes a lot of sense.thanks for the post.
Gravatar # re: Naming Things is Hard: Dictionaries
by Wayne at 2/23/2015 7:12 PM

Naming things is apparently one of the two hardest things in computer science (along with cache invalidation and of course off-by-one errors :)

This is the same pattern that I've been using for a while now and I really like it. Adding qualifiers to names is a really useful technique that can be applied to naming all sorts of things (type names, method names, database tables and other objects, etc).
Post A Comment