It’s increasingly popular for variables to be immutable by default. This makes the word “variable” a bit funny.

Also, I had a code review recently where a co-worker asked me to change some hard-coded strings to be constants. The strings, in this case, were argument names for a JSON API. So the API took e.g.

    "function" : "launchMissiles",
    "args" : {
        "target" : "Moscow",
        "type" : "ICBM",
        "count" : 17

The co-worker wanted all of the strings to be constants (except I think “Moscow” and “ICBM” came from user input and were thus variables). I thought it was reasonable to have “target”, “type”, and “count” be hard-coded. That’s because:

  1. Imagine that they were constants — what would you name them? final String ARG_FIELD_TYPE = "type"? That seems to make the code harder to read. Also, it repeats the value of the constant in its name. If tomorrow the value were changed to “model”, should we also change the name of the constant? To do so would be insane: changing a constant’s value shouldn’t entail changing its name. But to leave it the same would be monstrous: future readers would have no way of matching the function call to the API docs without resolving the value of each constant.

  2. Would it prevent misspellings? Not really. You could just as easily misspell a constant’s value as a hard-coded string’s value. If the string were repeated often, then maybe it could get occasionally typoed, but these weren’t repeated very often.

  3. And even if they were repeated, there would be no logical connection between the instances. The launchMissiles function happens to have a target argument, but so does the strstr function. But in the next release, maybe they’ll correct strstr to have better names (needle and haystack are the only correct names for strstr’s args).

Anyway, the point is that constants are often valuable for things that we do expect to change, and often less valuable for things that we don’t expect to change. So the “constant” name is a little funny too.

Next post: Greebled Teapot

Previous post: Rules; Reverence for religion