Saturday, December 19, 2015

Code readability: avoid negative statements

Negative statements are more difficult to read and not always the straightforward approach will result in the better code from the first attempt. Let's say the procedure should react on certain condition and ignore all overs. Compare these two snippets:

if (!isGreen) 
{
   StopMachine();
   TurnOnAlarm();
   RunForYourLife();
}
vs.
if (isGreen) return;
StopMachine();
TurnOnAlarm();
RunForYourLife();
The second one is more readable but more verbose (so as human language). Also the second one is obviously a separate method while the first one could be an inline code. In this case refactoring to the better readability resulted in more cohesive code.
If you're a tough C# programmer and reading both snippets is no brainer for you - consider this SQL nonsense:
DELETE FROM Cross_Reference_Between_Left_And_Right WHERE xId IN 
    (SELECT xId FROM Left_Table WHERE xNamePrefix NOT IN ('pro','contra'))
vs.
DELETE FROM Cross_Reference_Between_Left_And_Right WHERE xId NOT IN 
    (SELECT xId FROM Left_Table WHERE xNamePrefix IN ('pro','contra'))
For me personally, the first one is an eyesore.


© 2008-2013 Michael Goldobin. All rights reserved