DEV Community


Discussion on: Comments Are The Only "Code Smell"

merri profile image
Vesa Piittinen • Edited

Descriptive, long variable names can be good. However you should still be cautious with length, repetition and context.

If the file already defines context you don't need to repeat that context in each name especially if those variables are not exported.

If you have multiple variables that have repetition of the same things you may want to consider changing the names for visual clarity to make emphasis on how they are different. The more similarity there are between two variable names, and the longer they are, the harder it becomes for human mind to keep track of them.

const checkoutPageCurrentTotalInShoppingCart = getTotalFromShoppingCart();
const checkoutPageCurrentTotalWithTax = calculateSalesTax(checkoutPageCurrentTotalInShoppingCart);

I've seen people do things like this.

I would say currentTotalInShoppingCart is roughly the maximum length you should usually have for a variable name. There are OK exceptions. With this particular case I'd probably remove the word current for quicker distinction of differences, but even that decision depends on other variables in the file.

There are no absolute correct answers, but you can do your best to make the code reading process effortless.

bytebodger profile image
Adam Nathaniel Davis Author

Agreed on all fronts. As I stated in my article, I strongly prefer full-word-name variables. What I didn't explain in the article is that this often leads me to think - deeply - about the "exact", most-concise way to name a variable such that it is 1) clear, 2) descriptive, and 3) as short as possible.

It's not uncommon for me to refactor code because, when I was first writing it, I couldn't think of anything clearer than longYellowFruit. But later, while I'm reading the code, I realize that it's soooo much simpler to just call the variable banana.

I also share your frustration with context that is needlessly stuffed into the variable names. One great example of this annoyance is in objects. I see stuff like this far too often:

const names = {
  firstName: 'Adam',
  middleName: 'Nathaniel',
  lastName: 'Davis',

Despite my love of descriptive names, code like this drives me nuts. There's usually no reason for the repetition of Name inside each of the keys.

merri profile image
Vesa Piittinen

Yup, and my comment wasn't really to question anything in your article, I think it is very much on point. Went more for providing more food for thought for the others that end up here and might find this topic for the first time :)