Skip to main content Accessibility Feedback

Is naming things still hard?

This week on Mastodon, Cassondra Roberts asked

Quick survey for people who write web components:

Naming things is _____.

  • still hard.
  • not that hard anymore.
  • just show me the results.

It reminds me of the old axiom…

The two hardest problems in programming are naming things, cache invalidation, and off-by-one errors.

I answered “not that hard anymore,” but nearly 90 percent of survey respondents said it was still hard.

And I think that’s because Web Components don’t actually solve naming issues. A lot of the pain associated with naming things comes from either trying to be clever or creating things that try to do too much.

If you have small, narrowly focused functions and you keep your variable names, classes, and so on clear and obvious, naming things can be relatively easy.

For example, if you have a variable that stores a bunch of buttons, name it btns. If you might have more than one, add the type of button, like accordionToggles or something like that.

let btns = document.querySelectorAll('button');
let accordionToggles = document.querySelectorAll('[data-accordion]');

Don’t try to be clever. Don’t try to be terse.

Just name things what they are.

For variables and functions that return boolean values, start with a descriptor like is, has, contains, and so on.

let isPasswordValid = password.length > 16;
let hasAccess = user.permission.includes('admin');
let containsMerlin = ['Gandalf', 'Merlin', 'Radagast'].includes('Merlin');

Functions typically do things, so they should typically start with a verb.

function getUsername () {
	return localStorage.getItem('username');
}

function loginUser (username, password) {
	// ...
}

function saveSettings (settings) {
	// ...
}

If a function does multiple things in such a way that coming up with a verb-oriented name is challenging, split it up and make it do less!

This pattern of naming applies to CSS and custom elements, too.

.list-inline {}
.btn-primary {}

.text-large {}
.text-larger {}
.text-color-primary {}

.is-active {}
.has-submenu {}
<modal-toggle></modal-toggle>
<modal-content></modal-content>

<accordion-group></accordion-group>

<table-of-content></table-of-content>

So many of the problems I see around naming (and naming conflicts) and long-term maintainability of a project come down to developers being too clever or trying to do too much with any one particular variable, function, or style.

If that’s something you need help with, I have one consulting spot left for the start of 2024, and would love to work with you!