Pages

Tuesday, March 7, 2017

Get Rid of 'Magic Strings'

'magic string is an input that a programmer believes will never come externally and which activates otherwise hidden functionality.'


Basically is the term use to identify hard-coded strings inside our code. This strings are sometimes necessary in a program or at least can not be avoided in some situations (like dealing with legacy code).
The main problem with magic strings is that they are error prone, especially if used in more than one place, because we could mistype the magic strings and we will not get any compilation error or warning.

For example:


There are a couple of ways to deal with this.



The first one is to use an 'enum':


However this solution is not useful if our magic strings have more than one word or have an space character. For that Kind of situation the most common way to define them is as constant strings in an static class :



So Now we have all the magic string in one place where we can updated if we need to, and be sure we wont break our code.


And that, my friend, It's all!

No comments:

Post a Comment