I have the next piece of code:
internal static string GetNetBiosDomainFromMember(string memberName)
{
int indexOf = memberName.IndexOf("DC=", StringComparison.InvariantCultureIgnoreCase);
indexOf += "DC=".Length;
string domaninName = memberName.Substring(indexOf, memberName.Length - indexOf);
if (domaninName.Contains(","))
{
domaninName = domaninName.Split(new[] { "," }, StringSplitOptions.None)[0];
}
return domaninName;
}
I am making some parsings for AD, so I have some strings like "DC=", "objectCategory=", "LDAP://", ",", "." so and so. I found the above code more readable than the code below:(You may found the opposed, let' me know.)
private const string DcString = "DC=";
private const string Comma = ",";
internal static string GetNetBiosDomainFromMember(string memberName)
{
int indexOf = memberName.IndexOf(DcString, StringComparison.InvariantCultureIgnoreCase);
indexOf += DcString.Length;
string domaninName = memberName.Substring(indexOf, memberName.Length - indexOf);
if (domaninName.Contains(CommaString))
{
domaninName = domaninName.Split(new[] { CommaString }, StringSplitOptions.None)[0];
}
return domaninName;
}
Even I may have "DC" and "DC=", I should think in the names for this variables or divide these in two :(. Then my question: Should I avoid magic strings as possible?
UPDATED.
Some conclusions:
- There are ways to avoid using strings at all, which might be better. To achieve it could be used: static classes, enumerators, numeric constants, IOC containers and even reflection.
- A constant string help you to ensure you don't have any typos (in all references to a string).
- Constant strings for punctuation don't have any global semantic. Would be more readable to use these as they are ",". Use a constant for this case may be considered if that constant may change in the future, like change "," by "." (Have a constant may help you in that refactoring although modern tools as resharper do this without need of a constant or variable).
- If you only use it string once you do not need to make it into a constant. Consider however that a constant can be documented and shows up in documentation (as Javadocs). This may be important for non-trivial string values.