I find string constants mildly irritating, except in very specific circumstances.

I Don't Like String Constants

425 words.

I Don't Like String Constants

I don’t talk about software development very often, because it’s not a particularly crowd-pleasing subject for the masses. And, to be honest, developers tend to be opinionated, so conversations about development practices aren’t always fruitful.

Case in point: I don’t like string constants.

Or, I should say, I only like to create string constants in very specific circumstances. I don’t like them as a general default practice.

Those circumstances are as follows:

  1. If a string needs to be used more than once.
  2. If a string needs to be referenced in a unit test.
  3. If the string is part of some kind of language localization scheme. I don’t actually know how this is done in the modern world, but in olden times we would use identifier constants which were replaced with localized strings at runtime.

That’s about it. If a string doesn’t fall into one of those categories, I don’t mind putting them right in the middle of the code for everyone to see.

But there’s a prevalence of developers who like to put string constants at the top of every source code file as a matter of common practice, even if those strings are only referenced once in the entire codebase.

One situation that particularly aggravates me is the use of string constants for log messages.

As a devops developer, it’s very common for me to have to search a codebase for a log message that I’ve seen in a production log file somewhere. What happens is I’ll find the string of the message and it’ll be in a constant at the top of a file somewhere, completely stripped of the code context that generated the message. Then I have to do a second search to find where that string constant is actually used, so I can review the code.

It’s not the end of the world, it just seems like an extra step for no real purpose. (Unless it falls into one of the exceptions above.)

The older I get as a developer, the more minimalist I’ve become. I like simple code that’s easy to read and easy to maintain. Not just easy for me to read and maintain, but easy for a fresh developer out of college to read and maintain, or a developer who’s brand new to the language or codebase to read and maintain. The more I can avoid tricks and gimmicks and gotchas, the better.

End of lecture. This is why I don’t write about software development. It’s kind of boring.

Related

A thousand apologies, but I've disabled the third-party comment systems because I want to freeze the comment data for the time being. Your comments are still here, but I need to migrate them to a new thing I'm working on.

This is a homegrown DIY comment system I'm working on. It technically works but it hasn't been through extensive testing yet. Good luck. Go here to enter a comment on this post without Javascript.