BuiltSmart Home Blog Home Account Search
Why are magic strings a bad thing?
It's a common thing for new developers. Coding along, you need something more meaningful than a number or boolean to denote a specific action to take, so you use a string. For example:

messages.rendermessage(lblFeedback, "ERROR", "Some Message");

While this reads fine, it uses the magic string, ERROR, to denote functionality. You can understand it in the code, but the compiler can't, so it cannot check this value. What if you make a mistake in the spelling, change the case, or just use the wrong word?

So, how do you get around it - well, that's what constants are for...

Using something like this:

const MSG_TYPE_ERROR = "ERROR";

messages.rendermessage(lblFeedback, MSG_TYPE_ERROR, "Some Message");


The code is still readable, and now the compiler can actually check the value is well defined, and tell you if there is a problem or an unknown value in the code somewhere. Compilers are good at this, and its a good way to eradicate unknown and hard to trace bugs.