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)
{
    \_customerActionsByType\[customer.Type\].Invoke(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.

This article is part of the GWB Archives. Original Author: Steve Wilkes

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.