Make the Meanings of Keys and Values Obvious in Map/Dictionary/Lookup Types [VD12]

Make the Meanings of Keys and Values Obvious in Map/Dictionary/Lookup Types [VD12]

Tip VD12

Name “map” variables so that the meanings of keys and values are clear. This ensures the meaning of the variable is fully captured in the name and can help prevent bugs.

Maps, dictionaries, or other “lookup” types contain two kinds of objects - keys and values. You look up a value by giving the data structure a key. While such collection types can be named with just a plural for the values they contain (ex. employees), consider ways to embed information about both the keys and values in the variable name itself. That will enable easier verification and understanding of correctness when reading code. Some ways to do this are described below:

  • values_by_key - Or employees_by_name for the above example. The advantage of this approach is that when indexing into such a mapping type, the “keys” and “values” are kept close together. For example, Employee employee = employees_by_name[name] keeps the return type/value (Employee employee) close to the front of the mapping variable name (employees_...) and the indexing variable name (name) close to the indexing part of the mapping variable name (..._by_name).

  • keys_with_values - Or names_with_employees for the above example, communicating a pairing of names with employees. If iterating over a mapping type more than indexing into it, this can be another alternative that might make sense, matching the order of multiple loop iterators: var (name, employee) in names_with_employees.

Insights from every commit ad.png

See the following examples:

Naming map/dictionary/lookup types can get complicated if you have mixtures of more plural kinds of objects or multiple levels of nesting, so the above recommendations may need to be tweaked in some circumstances. For multiple levels of nesting, consider if you could introduce your own custom data type to reduce the problems. Otherwise, tweaking word order or adding additional suffixes can provide ways to give additional clarity when needed: NameToEmployeeMap, NameToEmployeeMapping, NameToEmployeeLookup.

 

Deep coding during work hours ad.png