Most comments on my code during reviews are about optimization. Tools like Resharper suggest code changes for cleaner code and optimization. But what about readability? Are most of today’s compilers smart enough to optimize the code?
The sample code below writes output to the console when writeToFile is false. Both lines do the same, but I prefer the first as it is more readable (to me).
if (false == writeToFile) Console.WriteLine("Whatever"); // OR if (! writeToFile) Console.WriteLine("Whatever");
With ILDASM the IL code is read from the compiled assembly. The code is exactly the same. Looks like the compiler is smart enough for this case.
Back in the day I learned C++. One of the program tests was the for statement. See the C# code below with that mindset. The first line got you flunked, the second was 1 point, the third got you 5 points and the last the full 10 points.
for (int i = 0; i < 10; i = i + 1) Console.WriteLine("output"); for (int i = 0; i < 10; i += 1) Console.WriteLine("output"); for (int i = 0; i < 10; i ++) Console.WriteLine("output"); // Below is different! for (int i = 0; i ++ < 10; ) Console.WriteLine("output");
Again getting the IL code from the assembly showed the first three lines resulted in the same code, where the last was different.
Debugging the code will show the behavior is slightly different (hint: when is the index incremented) So be warned not to optimize the code so it changes behavior!
I’ll be programming my code for readability no matter what the tools suggest.
“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”
– Martin Golding