Daily Archives: December 13, 2013
Good Practice (Part 2)
Today a quick follow-up on code legibility.
As usual all should be self-explanatory.
static void BadPractice5() { string a = null; string b = "hello"; string c = string.Empty; string s; if (a != null) s = a; else if (b != null) s = b; else s = c; } // static void GoodPractice5() { string a = null; string b = "hello"; string c = string.Empty; string s = a ?? b ?? c; } //
static void BadPractice6() { string s = "12345"; // s.Length is called multiple times for (int i = 0; i < s.Length; i++) { Console.WriteLine(s[i]); //s = "a"; // uncomment to see that "i < s.Length" is evaluated over and over again } } // static void GoodPractice6() { string s = "12345"; for (int i = 0, n = s.Length; i < n; i++) Console.WriteLine(s[i]); // s.Length is only called once } //
static void BadPractice7() { string s = string.Empty; for (int i = 0; i < 100; i++) s += i.ToString() + " "; Console.WriteLine(s); Console.ReadLine(); } // static void GoodPractice7() { // Use the StringBuilder class for multiple string concatenations! // Strings are immutable, concatenations are very slow. string s = string.Empty; StringBuilder lStringBuilder = new StringBuilder(); for (int i = 0; i < 100; i++) { lStringBuilder.Append(i); lStringBuilder.Append(" "); } s = lStringBuilder.ToString(); Console.WriteLine(s); Console.ReadLine(); } //
static void BadPractice8() { string s = string.Empty; do { s = Console.ReadLine(); if (s == string.Empty) break; } while (true); } // static void GoodPractice8() { string s = string.Empty; while (true) { s = Console.ReadLine(); if (string.IsNullOrEmpty(s)) break; } } //
static void BadPractice9() { var lList = Enumerable.Range(1, 10); // imagine it is a grow only list // bad foreach (var i in lList) { Console.WriteLine(i); } Console.ReadLine(); // also bad for (int i = 0, n = lList.Count(); i < n; i++) { Console.WriteLine(lList.ElementAt(i)); } Console.ReadLine(); } // static void GoodPractice9() { var lList = Enumerable.Range(1, 10); // imagine it is a grow only list // This is for real hardcore multithreading coders: // If poosibe walk through the list backwards and you can add elements // to the list concurrently without the need to synchronize anything. // No lock() required in a multithreading environment! for (int i = lList.Count() - 1; i > -1; i--) { Console.WriteLine(lList.ElementAt(i)); } Console.ReadLine(); } //