DEV Community

Kittipat.po
Kittipat.po

Posted on

Coding Tips #1: Name Your Maps Like You Care About Your Future Self

Let’s say you’re reading some Go code and stumble upon this:

for _, transaction := range transactions {
    customer := customerMap[transaction.Ref]
    sendReportEmail(customer.Email)
}
Enter fullscreen mode Exit fullscreen mode

At first glance, it works. But if you’re the poor soul maintaining this code, questions start flooding in:

  • What is customerMap actually mapping?
  • What is transaction.Ref referring to? Is it a Customer ID? A Card ID? A National ID?
  • What does that string key even represent?

You’re stuck. You can’t proceed confidently until you understand what customerMap is mapping from and to.

So, what’s your next move?
If you’re lucky 🍀, you find this somewhere earlier in the code:

customerMap := groupCustomerByCustomerId(customers)
Enter fullscreen mode Exit fullscreen mode

Ah! Now it clicks. customerMap maps from CustomerID to Customer. So transaction.Ref must be the Customer ID. You make a mental note and continue reading.

But if you’re not lucky? 😩 You find this instead:

customerMap := buildMapFromCustomers(customers)
Enter fullscreen mode Exit fullscreen mode

Now you have to dive into that function just to figure out one simple thing: what’s the key?

Remember, all you wanted was to tweak the logic slightly. But now you’re deep in unrelated code, just trying to answer a basic question: what does this map do?

🧠 So What’s the Fix?

Name your maps clearly and semantically.
Instead of this:

customerMap := groupCustomerByCustomerId(customers)
Enter fullscreen mode Exit fullscreen mode

Use this:

customerIdToCustomer := groupCustomerByCustomerId(customers)
Enter fullscreen mode Exit fullscreen mode

Now the loop reads beautifully:

for _, transaction := range transactions {
    customer := customerIdToCustomer[transaction.Ref]
    sendReportEmail(customer.Email)
}
Enter fullscreen mode Exit fullscreen mode

Even without looking elsewhere in the code, you immediately know:

  • The key is a CustomerID
  • The value is a Customer
  • transaction.Ref is likely a Customer ID

And just like that, you can keep reading without breaking your flow. ✅

🔁 In General: Use keyToValue Naming for Maps

When naming maps, this format is gold:

keyToValue := make(map[KeyType]ValueType)
Enter fullscreen mode Exit fullscreen mode

Examples:

  • userIdToEmail
  • orderIdToStatus
  • productCodeToPrice

Top comments (0)