Code Simplified

Working with junior developers through out my years, I have seen some funky and fun ways of coding.  The three styles I have seen the most are the following.    I have come up with BEFORE and AFTER examples.  Now the AFTER is just my opinion on how the code should be rewritten, but is not necessary the only way.

BEFORE

           String strDelim = “;,”;
           Char[] delimiter = strDelim.ToCharArray();

           String[] emails = to.Split(delimiter);

AFTER

           Char[] delimiter = new[] { ‘;’, ‘,’ };

           

String[] emails = to.Split(delimiter);


EXPLANATION
I prefer this rewrite because it is smaller in number of lines and it is less instructions to the compiler.  Although this example was 3 lines rewritten as two and seems small; in a large program, it adds up if done enough. 

BEFORE
           String answer = “”;
           if(rdButton.Checked == true)
           {
                      answer = “Test 1”;
           }
           else
           {
                      answer = “Test 2”;
           }

AFTER
           String answer = rdButton.Checked ? “Test 1” : “Test 2”;

EXPLANATION
This rewrite uses an old C style called Immediate IF.   This takes your simple if block statement and breaks it down to one line.  The other change is the == true was removed. Since the rdButton.Checked already returns true / false, it is not required to conduct an additional check.

BEFORE
           String rpt = “Error at Line: ” + lineNumber + “n” + “Description: ” + 

AFTER
           String rpt = String.Format(“Error at Line: {0}nDescription: {1}”, lineNumber, Description);

EXPLANATION
This change uses the String.Format command to take a pre-written string and inject the variables into their appropriate position within the string.  This is probably more of a preference of mine, but I think it looks cleaner.   The code does run faster when you are not adding string after string together, but with today’s processors and memory capabilities the savings is probably not much.  The main benefit is you can define these pre-written strings once and used them in this manner multiple times throughout the same piece of code. It will look cleaner overall.