jump to navigation

Please Stop Naming Your Strings with Constants November 16, 2015

Posted by PythonGuy in Uncategorized.

A long time ago, people used bit fields to record boolean attributes. Thankfully, it seems we don’t do that anymore. The only reason we did it was because memory was scarce and processors were slow. With the abandonment of bitfield went the constants that were required to manipulate the bitfields.

Now we also have enums. A common type of enum is “type”, which tells you what type of object you are looking at. (The very idea that you can ask an object what type of object it is suggests that maybe strong typing is the way to go. Meaning, a type system where every object knows exactly what it is.)

In code, I often see people assign the various values of the enum to global, static variables, AKA constants. They then use these variables to refer back to the values they represent.

It used to be that, again due to memory constraints, we would use integers to list the various types of objects. Nowadays, that’s absurd. Just use a string that humans can read to tell us what the object type is.

Now that we use strings for the enum values, it makes little sense to keep the practice of assigning the enum values to constants. Just don’t do that. It’s silly.

To understand why it’s silly, consider the case where I am in right now. I’d like to interface with a Java API, but I only have access to the Java implementation. Rather than write “CUSTOMER”, the Java code says, UserType.CUSTOMER. I have to go look up what that is. If, instead, the coder wrote just “CUSTOMER”, no look up would be needed.

I really can’t imagine a scenario where having constants with the exact same name as the string it points to is useful. I mean, if you want to find everywhere you refer to customer types, just look up the string “CUSTOMER” and you’re golden.

I suppose some people like it because if they misspell the constant, the compiler will warn them. These seem to be the same type of people that think strict variable typing solves more problems than it causes.