Recently, a batch of code has been maintained, including the use of a pile of if... With 8 or 9 layers of nesting in many cases, which is extremely painful. Therefore, search for some ways to reduce if...else to improve the code and write a simple summary.
The first:
Before optimization
if (measuredValue > 8) return 5 * measuredValue * measuredValue - 3; if (measuredValue > 4) return 4 * measuredValue - 2; if (measuredValue >= 0) return 3 * measuredValue - 1; return 2 * measuredValue;
After using list and linq optimization (excerpt: https://www.linkedin.com/pulse/if-less-programming-c-jiri-pokorny)
using System; using System.Linq; namespace ConsoleApp1 { internal class Program { private static readonly MeasureTransform[] Transformations = new MeasureTransform[] { // This order determines the order of judgment new MeasureTransform(m => m > 8, m => 5 * m * m - 3), new MeasureTransform(m => m > 4, m => 4 * m - 2), new MeasureTransform(m => m >= 0, m => 3 * m - 1), new MeasureTransform(m => true, m => 2 * m) }; private static void Main(string[] args) { var executor = Transformations.First(t => t.CanApply(16)); Console.Write(executor.Transform(16)); } } internal class MeasureTransform { public MeasureTransform(Func<int, bool> canApply, Func<int, int> transform) { CanApply = canApply ?? throw new ArgumentNullException(nameof(canApply)); Transform = transform ?? throw new ArgumentNullException(nameof(transform)); } public Func<int, bool> CanApply { get; set; } public Func<int, int> Transform { get; set; } } }
Second: use logical operators to improve
using System; using System.Linq; namespace ConsoleApp1 { internal class Program { private static void Main(string[] args) { int a = 10; int b = 10; // Before optimization if (a > 5) { if (b > 10) { Console.Write(""); } } // After optimization if (a > 5 && b > 10) { Console.Write(""); } } } }
Third: see if there is any redundant judgment from the perspective of business logic
using System; using System.Linq; namespace ConsoleApp1 { internal class Program { private static void Main(string[] args) { System.UInt32 a = 10; int b = (int)a + 10; // Before optimization if (a > 10) { if (b > 10) { Console.Write(""); } } // After optimization if (a > 10) { Console.Write(""); } } } }
Fourth: use ternary operators
Before optimization
namespace ConsoleApp1 { internal class Program { private static void Main(string[] args) { System.UInt32 a = 10; uint c; if (a > 10) { c = a; } else { c = a + 10; } } } }
After optimization
using System; using System.Linq; namespace ConsoleApp1 { internal class Program { private static void Main(string[] args) { System.UInt32 a = 10; int b = (int)a + 10; // Before optimization var c = a > 10 ? a : a + 10; } } }
Fifth: too many if..else if... Are inefficient. Use switch...case... Or watch it.
Sixth: use dependency injection, reflection and so on from the architecture level https://www.c-sharpcorner.com/forums/how-can-i-remove-multiple-if-statement.