Daniel Irvine on building software
Minimize control statements
1 February 2013
If you have this structure
if (condition) foreach (var outputMessage in funcA) yield return outputMessage; else foreach(var outputMessage in funcB) yield return outputMessage;
Refactor it to this:
var func = condition ? funcA : funcB; foreach(var outputMessage in func) yield return outputMessage;
Before you had one conditional, two loops and two returns. Now you have one conditional, one loop and one return--in other words, a it’s a lot simpler. It’s minimal.
Minimalism is important in coding. You don’t want to be so minimalist that you write cryptic, unintelligible code, but you definitely want to minimize control structures as much as possible.
The reason is primarily one of cost: more code means greater cost over the lifetime of the source, which could be many years. Too often developers forget that up-front development is just a tiny fraction of the total cost of code. The code will be read, comprehended, discussed, documented and debugged perhaps hundreds of times throughout its lifetime. Spare a thought for those poor developers who come after you--make their life easy and minimize your output!