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:

//To verify a seting
if (userType == "Admin")
{
IsAdmin = true;
}
//Or To define a Process inside a function
if (process == "CreditExtension")
{
calculateInterest = true;
}
//That could be called like...
this.ExecuteCalculationX("CreditExtension", clientId: 567)

There are a couple of ways to deal with this.



The first one is to use an 'enum':

//Sample A
public enum UserType
{
Admin,
User
}
//To verify a seting
if (userType == UserType.Admin)
{
IsAdmin = true;
}
//Sample B
public enum OperationName
{
CreditExtension,
Payment,
SaleAssets
}
//Or To define a Process inside a function
if (process == Enum.GetName(typeof(OperationName), OperationName.CreditExtension))
{
calculateInterest = true;
}
//That could be called like this ...
this.ExecuteCalculationX(Enum.GetName(typeof(OperationName), OperationName.CreditExtension), clientId: 567)

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 :

public static class OperationName
{
public const string CreditExtension = "Credit Extension" ;
public const string Payment = "Payment Made" ;
public const string SaleAsset = "Sale Assets" ;
}
//That way we can use them in the following way:
if (process == OperationName.CreditExtension)
{
calculateInterest = true;
}
this.ExecuteCalculationX(OperationName.CreditExtension, clientId: 567)


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