Wednesday, March 30, 2022

Kill the Switch statements

Has I continue my work as a Software Engineer I get exposed to a plethora of development styles, but one common element is the "Switch" statements. I don't believe this is the best approach. Why? Because if there is another condition that needs to be evaluated you need to modify the code that has already been tested and might be in production, this is an opportunity to inject a new bug.

I will being writting this in C# using VS 2019, but the principle should apply across syntax.

Here is a smaple of what I am speaking of:

The below code tries to format a double of number
if (string.IsNullOrWhiteSpace(finalDataFormatString)) ----This line verifies that the condition being evalutated is not empty or just a blank value
{
switch (finalDataTypeName) -- Evaluating condition
{
case "CURRENCY": -- condition
finalDataFormatString = "$#,##0.00";
break;
case "PERCENT":
finalDataFormatString = "#,##0%";
break;
case "PERCENT-ONE-DECIMAL":
finalDataFormatString = "#,##0.0%";
break;
case "PERCENT-TWO-DECIMALS":
finalDataFormatString = "#,##0.00%";
break;
case "INTEGER":
finalDataFormatString = "#,##0";
break;
case "INTEGER-NO-COMMAS":
finalDataFormatString = "###0";
break;
case "FLOATING-POINT":
case "FIXED-POINT-TWO-DECIMALS":
case "DOUBLE":
case "SINGLE":
case "DECIMAL":
finalDataFormatString = "#,##0.00";
break;
case "FIXED-POINT-ONE-DECIMAL":
finalDataFormatString = "#,##0.0";
break;
}
}


So, what's the problem - it seems pretty straight forward. Well the problem comes in if/when the customer want add a "PERCENT-THREE-DECIMALS" or a "FIXED-POINT-TWO-DECIMAL". You would need to modify this code to include the new conditions.
So what can be done: Well what I did was I created a resource file and called it FinalDataFormat. The usable column are Name and Value
Name Value Comment
CURRENCY $#,##0.00
PERCENT #,##0%
PERCENT-ONE-DECIMAL #,##0.0%
FLOATING-POINT #,##0.00
DOUBLE #,##0.00


I think you understand how the resource file is created. Once the file is created I replaced the 33 lines of code with the following:
string resVal = FinalDataFormat.ResourceManager.GetString(finalDataTypeName.ToUpper()); if (!string.IsNullOrWhiteSpace(finalDataFormatString)) { finalDataFormatString = resVal;

The first line replaces the whole switch statement, it pulls the value from the resource file based on the finalDataType, then we check for a null or whitespace, if this passes, it sets the finalDataFormatString = to the value.
This is a very simple switch statement, what if there is something more complicated? That is going to be another post.

No comments: