Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice on IF/ELSE Statement Order

Which is a better practice? (I'm coding in .Net if that makes a difference)

IF condition = true THEN
   ...true action--even if rare...
ELSE
   ...action
END IF

or

IF condition = [most common condition] THEN
   ...most common action....
ELSE
   ...least common action
END IF
like image 717
Jeff Avatar asked Aug 20 '09 13:08

Jeff


2 Answers

According to Steve McConnell, author of Code Complete, you should

"Put the case you normally expect to process first. This is in line with the general principle of putting code that results from a decision as close as possible to the decision...[putting the normal case after the if] puts the focus on reading the main flow rather than on wading through the exceptional cases, so the code is easier to read overall."

Code Complete, 2nd Edition, pages 356-357.

like image 117
Matthew Nizol Avatar answered Oct 17 '22 03:10

Matthew Nizol


Go with the most readable version for your specific case, and by the way, don't compare a boolean expression to true and false. Use condition and Not condition (!condition in C#.)

if (condition == true) // bad
if (condition) // better 
like image 26
mmx Avatar answered Oct 17 '22 03:10

mmx