Are hard-coded STRINGS ever acceptable

hard-codinglanguage-agnosticliteralsstring-literals

Similar to Is hard-coding literals ever acceptable?, but I'm specifically thinking of "magic strings" here.

On a large project, we have a table of configuration options like these:

Name         Value
----         -----
FOO_ENABLED  Y
BAR_ENABLED  N
...

(Hundreds of them).

The common practice is to call a generic function to test an option like this:

if (config_options.value('FOO_ENABLED') == 'Y') ...

(Of course, this same option may need to be checked in many places in the system code.)

When adding a new option, I was considering adding a function to hide the "magic string" like this:

if (config_options.foo_enabled()) ...

However, colleagues thought I'd gone overboard and objected to doing this, preferring the hard-coding because:

  • That's what we normally do
  • It makes it easier to see what's going on when debugging the code

The trouble is, I can see their point! Realistically, we are never going to rename the options for any reason, so about the only advantage I can think of for my function is that the compiler would catch any typo like fo_enabled(), but not 'FO_ENABLED'.

What do you think? Have I missed any other advantages/disadvantages?

Best Solution

If I use a string once in the code, I don't generally worry about making it a constant somewhere.

If I use a string twice in the code, I'll consider making it a constant.

If I use a string three times in the code, I'll almost certainly make it a constant.