Code Style
Logic section
Use blank lines to separate your code into logical sections
Instead of:
var sb = new StringBuilder();
sb.Append(mainId);
if (sb.Length > 0 && !string.IsNullOrEmpty(secondaryId))
{
sb.Append("_");
}
sb.Append(secondaryId);
sb.Append(extraText);
You can write:
var sb = new StringBuilder(); // section of object creation
sb.Append(mainId); // section of appending mainID
// section of checking for mainID and secondaryID
if (sb.Length > 0 && !string.IsNullOrEmpty(secondaryId))
{
sb.Append("_");
}
sb.Append(secondaryId);
sb.Append(extraText);
The same for the rest part.
Long condition in if statement
Don't use long condition in if statement. It's not readable.
Instead of:
if (sb.Length > 0 && (char.IsNumber(sb[0]) || '+'.Equals(sb[0]) || '-'.Equals(sb[0])))
You can use:
isNum = char.IsNumber(sb[0]);
isPlus = sb[0].Equals('+');
isMinus = sb[0].Equals('-');
if (sb.Length > 0 && (isNum || isPlus || isMinus)
{
sb.Insert(0, "N");
}
We can move deeply and I want to get rid of this long if statement:
if (sb.Length > 0)
{
isNum = char.IsNumber(sb[0]);
isPlus = sb[0].Equals('+');
isMinus = sb[0].Equals('-');
if (isNum || isPlus || isMinus)
{
sb.Insert(0, "N");
}
}
I still don't like this if construction, I'll extract this code into separate method. Before this I'll create an array of legal symbols
if (sb.Length > 0)
{
isNum = char.IsNumber(sb[0]);
isLegalSymb = isLegalSymb(sb[0]);
if (isNum || isLegalSymb)
{
sb.Insert(0, "N");
}
}
Separate method for checking if character is legal.
private static bool isLegalSymb(char symb) {
string[] legalSymb = { "+", "-" };
for (int i = 0; i < legalSymb.Length; i++) {
if (symb.Equals(legalSymb[i])) {
return true;
}
}
return false;
}
Comments
Your code is not always obvious and other developers may don't understand anything without a context of this code.
In such situations you can provide more comments to make our life more easy.
It relates to your code:
foreach(var illegalChar in IllegalCharacters) {
sb.Replace(illegalChar.ToString(CultureInfo.InvariantCulture), string.Empty);
}
I'm also confused with:
private const string IllegalCharacters = "\\" + "\"" + "'#,.[]{}" + " ";
I'll again extract this code into separate method:
replaceAllBannedCharacters(sb);
Separate method for replacing all banned symbols:
private static void replaceAllBannedCharacters(StringBuilder sb) {
string[] bannedSymb = { "#", "'", ".", "[", "]", "{", "}", "," };
for (int i = 0; i < bannedSymb.Length; i++) {
sb.Replace(bannedSymb[i], string.Empty);
}
}
Naming
mainId can be replaced with firstID
secondaryId can be replaced with secondID