Designing Custom Return Values ββin C #
I was provided with a spreadsheet with possible return codes and their descriptions from a third party web service. They look like this (simplified):
Code Description
M1 Some description of M1
M2 Some description of M2
M3 Some description of M3
M4 Some description of M4
P1 Some description of P1
P2 Some description of P2
N1 Some description of N1
N2 Some description of N2
In the above list, M codes are classified as Match , P codes are Partial Match , and I codes are No Match .
In a C # function, these return values ββare handled using the switch
case
following:
...
switch(returncode)
{
case "M1":
case "M2":
case "M3":
case "M4":
DoSomethingForMatch(ReturnCodeDescription);
break;
case "P1":
case "P2":
case "P3":
case "P4":
DoSomethingForPartialMatch(ReturnCodeDescription);
break;
case "N1":
case "N2":
default:
DoSomethingForNoMatch(ReturnCodeDescription);
break;
}
While the reverse codes look the same, there is no naming convention. There may be other return codes in the future that may have a different format. But they will still fall into one of three categories: match, overlap, and no match.
If there are new return codes in the future, with this design I have to update the code and rebuild, redistribute, etc.
There must be a better way to do this than hard-code the return values ββin code like this. I would like to ask for your advice on how to do this in a customizable, scalable way. Does keeping all possible codes and descriptions in the DB table the best way to accomplish this? Thank.
source to share
If the return codes are somewhat predictable for future use, you can use regular expressions.
The pseudocode will look like
RegEx fullMatch = new RegEx("some_reg_ex_here");
RegEx partialMatch = new RegEx("some_reg_ex_here");
if (fullMatch.IsMatch(returnCode)
DoSomethingForMatch(ReturnCodeDescription);
else if (partialMatch.IsMatch(returnCode)
DoSomethingForPartialMatch(ReturnCodeDescription);
else
DoSomethingForNoMatch(ReturnCodeDescription);
source to share
I would be tempted to convert to an enumeration.
Code.cs
enum Code
{
Unknown = 0,
Match = 'M',
PartialMatch = 'P',
NoMatch = 'N'
}
static class CodeExtensions
{
public static Code ToCode(this string value)
{
value = value.Trim();
if (String.IsNullOrEmpty(value))
return Code.Unknown;
if (value.Length != 2)
return Code.Unknown;
return value[0].ToCode();
}
public static Code ToCode(this char value)
{
int numericValue = value;
if (!Enum.IsDefined(typeof(Code), numericValue))
return Code.Unknown;
return (Code)numericValue;
}
}
Using
var code = returnCode.ToCode();
switch (code)
{
case Code.Match:
DoSomethingForMatch(ReturnCodeDescription);
break;
case Code.PartialMatch:
DoSomethingForPartialMatch(ReturnCodeDescription);
break;
default:
DoSomethingForNoMatch(ReturnCodeDescription);
break;
}
source to share