language-agnosticcoding-stylemagic-string

Should I avoid magic strings as possible?


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:


Solution

  • I would certainly make constants for the actual names like "DC" and "objectCategory", but not for the punctuation. The point of this is to make sure you don't have any typos and such and that you can easily find all of the references for the places that use that magic string. The punctuation is not really part of that.

    Just to be clear, I'm assuming the magic strings are things that you have to deal with, that you don't have the option of making them a number defined by a constant. As in the comment to your question, that's always preferable if that's possible. But sometimes you must use a string if you have to interface with some other system that requires it.