Delphi:Nested IF Replacement
Every once in a while coding an application involves forking - i.e. selecting one of several routes forward - based on the evaluation of the states of three or more boolean conditions. Most novice programmers end up writing complex spaghetti code with a myriad of nested IF..THEN..ELSE statements. Such code is very hard to maintain and even harder to understand. We present a more elegant and computationally efficient alternative.
procedure TExplainThat.Fork(Hungry,Tired,Sleepy:Boolean); var i:Integer; begin i:=ord(Hungry) or (ord(Tired) shl 1) or (ord(Sleepy) shl 2); case i of 0:GetBored;//Nothing to do 1:CookAndEat;//Just hungry so cook first 2:TakeANap;//Tired so rest 3:OrderAPizza;//Can't be bothered cooking 4:GoToBed;//Sleep 5:SnackThenSleep;//Hungry AND sleepy so grab a quick snack and then goto bed 6:GoToBed;//Tired AND Sleepy 7:SnackThenSleep;//Tired and sleepy but must eat something end; end;
- This technique is computationally better because we establish the various fork routes once and for all at coding-time rather than getting the processor to run
if..then..elsetests each time a decision is required. - For clarity, put a comment after each evaluated condition. The action to be taken should be a simple procedure call, not in-place code inside a
begin..endblock.
Certain conditions can be mutually exclusive so no action will be required for the integer combination that corresponds to them. In such cases, you should nevertheless put in an explanatory comment.