static void Main(string[] args) { // Given three expressions... bool Expression1 = true; bool Expression2 = true; bool Expression3 = true; /* You may run across code that looks something like this. * Using this type of construct has a bad smell, * since the if/else shortcut has multiple expressions. */ bool x; x = (Expression1) ? ((Expression2) ? ((Expression3) ? true : false) : false) : false; Console.WriteLine(x); // Writes True /* By expanding it into if statements you can determine * where the common result is -- in this case "false" -- * is found, and why. */ if (Expression1) if (Expression2) if (Expression3) x = true; else x = false; else x = false; else x = false; Console.WriteLine(x); // Writes True /* Since x is only set to True when all * three expressions are true, * the code can be refactored as follows: */ x = false; if (Expression1 && Expression2 && Expression3) x = true; Console.WriteLine(x); // Writes True // Now, you can refactor the code so that it // makes better sense. x = (Expression1 && Expression2 && Expression3) ? true : false; Console.WriteLine(x); // Writes True }
nug·get (nug!it)
n.
1. A small, solid lump, especially of gold.
2. A small compact portion or unit: nuggets of information.
Wednesday, March 23, 2011
Refactoring the Shortcut IF statement
Labels:
.NET
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment