Bob Nystrom’s Four Rules for Better Naming in Programming
Yesterday, I re-discovered Bob Nystrom’s Long Names Are Long blog post.
When he was doing code reviews at Google, he noticed a lot of code creating “identifiers that were too damn long.” So he wrote this blog post to provide guidelines on how to create better identifiers.
Here’s my summary of Bob’s four rules:
1. Omit words that describe the variable’s type or the method’s parameters⌗
It’s redundant to put the type in the variable’s name.
Doubly so when you’re using a statically-typed language. If you’re using a dynamically-typed language, it doesn’t take long to scan the code and infer the variable’s type. Don’t make the reader sound like an echo.
// Bad variable name
var userNameMap map[int]string
// Better variable name
userNameByID := make(map[int]string)
The same advice holds for method names. Don’t describe the parameters in the method’s name.
// Bad method name
func mergeUsers(users []User)
// Better method name
func merge(users []User)
2. Don’t cram everything you know about the variable into its name⌗
The variable name shouldn’t describe everything. That’s the role of the variable definition. For example, ultimateRareBossSword is a bad name, but sword is a better name.
In this example, I’ve named a variable “sword,” but I can look at its definition to see it has a rarity score of 10.
type Sword struct {
rarity int
name string
}
sword := Sword{rarirty: 10, name: "Tri-tip Dagger"}
3. Use the surrounding context to your advantage⌗
Variables and methods are always used within some context. There’s no reason to repeat the information already defined by the context. Use that to your advantage to create shorter names.
// Bad: dog is redundant in dogName and dogAge because of the
// given context
type Dog struct {
dogName string
dogAge int
}
4. Say no to fluff and jargon⌗
Calling something a “manager” doesn’t convey any image to the reader about what the thing does. Does it do performance evaluations? Give raises?
Fluff and jargon provide no valuable information about the thing we’re naming. They’re too vague, so avoid using them in names. Some words to avoid: manager, data, value, instance, and object.
Bob’s rule of thumb is, “Ask yourself ‘Would this identifier mean the same thing if I removed the word?’ If so, the word doesn’t carry its weight: vote if off the island.”
Thanks for reading! Let me know what you think of this post on Twitter.