I'm taking on a project from a previous programmer. My goal is to make it a bit smaller and hopefully better. Originally the code has a bunch of length checks and Booleans as shown below.
C#
string[] splitStrArray = SNString.Split('-');
string part1 = splitStrArray[0];
string part2 = splitStrArray[1];
string part3 = splitStrArray[2];
bool part1ok = false;
bool part2ok = false;
bool part3ok = false;
if (part1.Length == 3)
{
part1ok = true;
}
if (part2.Length == 8)
{
part2ok = true;
}
if (part3.Length == 3)
{
part3ok = true;
}
if(part1ok && part2ok && part3ok)
{
return true;
}
else
{
return false;
}
Is it a good practice to keep that or should I change it to my following idea?
string[] splitStrArray = SNString.Split('-');
string part1 = splitStrArray[0];
string part2 = splitStrArray[1];
string part3 = splitStrArray[2];
if(part1.Length == 3 && part2.Length == 8 && part3.Length == 3)
{
return true;
}
else
{
return false;
}
Basically a barcode is scanned, and a SN is passed to the application. The goal is to make sure the SN scanned is of a format XXX-XXXXXXXX-XXX. Sometimes there are occurrences of SNs that are formatted XXXXXXXXXXXXX or XXX-XXXXXXXXXX not complete or missing a specific dash.
Split
returns an array with exactly four elements? If you already know that there are exactly three hyphens in the string, then whatever code ensures that invariant should ensure the other invariants are met. If you do not already know that, then your program can crash. Either way, something seems wrong here. \$\endgroup\$