Question

In data processing, I frequently need to create a lookup data structure to map one identifier to another. As a concrete example, let's take a structure which holds a 1-to-1 mapping between a country's 2 character code and its full name. In it we would have

AD -> Andorra   
AE -> United Arab Emirates  
AF -> Afghanistan

What's a good name for the variable that would hold this map? Some ideas (I'll use camel-case names):

countryNameByCode
nameByCodeLookup
nameCodeLookup
codeToName
Was it helpful?

Solution

My vote would be for codeToName in this particular case, and I guess that generalizes. That's not to say that it's the name I would have chosen myself in all cases; that depends a lot on scope, further encapsulation, and so on. But it feels like a good name, that should help make your code readable:

String country = codeToName["SV"];

Looks fairly nice, should be easily understandable by anyone. Possibly change the word "code" to something more precise ("countrycode" would be my next choice).

OTHER TIPS

country_name = countries_by_code[country_code]

It passes the “telephone dictation” test, and also sounds more like natural language.

I like to use plurals for collections.

countryNames

Edit: countryCodes is wrong because you are mapping from a code to a name.

I usually do it this way:

countryCodeMappingByName

Or if the mapping is unique, just simply:

countryCodeMapping

RWendi

Use something which sounds right when pronouncing it. This also means name your key variables appropriately. Example:

countryName = countries[countryCode];

This makes perfect sense - you give countries a countryCode, and it returns a countryName. This would be redundant:

countryName = countryCodesToNames[countryCode];

In C#, I'd call a type that does this CountryCodeToNameMapping. Usually I'd call a variable countryCodeToNameMapping, but in certain very restricted contexts (e.g., lambdas), I'd probably call it c or m.

Another vote for just pluralizing what you're mapping to.

eg. country = countries[code]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top