by Leon Rosenshein

Naming Is Hard

There are only two hard things in Computer Science: cache invalidation and naming things.
-- Phil Karlton

We all know that. So what do you do? First, be consistent. A foolish consistency may be the hobgoblin of little minds, but this kind of consistency is not foolish.

Names, method or member, internal or external, form the basis of a ubiquitous language. Language lets us communicate what’s inside our heads with others, and having a consistent language reduces cognitive load. And as I’ve mentioned before, reducing cognitive load is a good thing. For example, if you decide to have a method that gives you the number of entries in an array called Length(), then you should have the same for sets, lists, maps, and any other collection. Calling it Length in some, Count() in others, and having a member variable called NumberOfItems for one will drive your users insane.

And not just consistency in names, but in style. Again, whether it’s CamelCase, SCREAMING_SNAKE_CASE, or kebab-case, pick one and stick with it. And when I say pick one, I don’t mean pick one for yourself and use it everywhere, I mean pick one for something with very clear boundaries, like a team, or a company, and then stick with it. Consistency is your friend.

That’s just the first thing though. If you are consistent your customers will eventually figure out your pattern/style and be able to follow along. Having a good name is also important. Something that lets the reader know immediately what the thing is/does. So what goes into a good name?

It should be Short, Intuitive, and Descriptive. Something like documentPageCountsectionPageCount, and chapterPageCount. Just from looking you can tell that they’re page counts for different parts of a document. It’s a Count, so it measures things. You don’t expect it to change as you move around in the document like pageNumber might.

Manage your context. Think about those different counts. The first word sets the basic context, and each word after gets more precise. By the time you get to Count you know exactly what you’re talking about. And always be consistent (there’s that word again) with which way the context increases. Order matters.

Speaking of context, avoid stuttering. If you have a context, use it to disambiguate. Don’t make the name longer to re-add the context. gofmt even has an error message just for that case, type name will be used as by other packages, and that stutters;

And finally, if you’re doing something, be very clear about what you’re doing. Put the verb up front. And be precise. If you’re updating an element in a collection then by overwriting, call it overwriteElement or updateElement. If you’re replacing an element in a collection then call it replaceElement. And whatever you do, don’t call it createElement if the element exists.

But again, and most importantly, be consistent. This is another example of when not to surprise your customer.