Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to put in the IF block and what to put in the ELSE block?

This is a minor style question, but every bit of readability you add to your code counts.

So if you've got:

if (condition) then
{
   // do stuff
}
else
{
   // do other stuff
}

How do you decide if it's better like that, or like this:

   if (!condition) then
   {
     // do other stuff
   {
   else
   {
     // do stuff
   }

My heuristics are:

  1. Keep the condition positive (less mental calculation when reading it)
  2. Put the most common path into the first block
like image 855
WW. Avatar asked Oct 03 '08 12:10

WW.


People also ask

What's an example of an if/then else statement?

The if / then statement is a conditional statement that executes its sub-statement, which follows the then keyword, only if the provided condition evaluates to true: if x < 10 then x := x+1; In the above example, the condition is x < 10 , and the statement to execute is x := x+1 .

What is the purpose of an if/then else block?

The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false . You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion.

What is the correct syntax for the if-else block?

The If-Else statement The general form of if-else is as follows: if (test-expression) { True block of statements } Else { False block of statements } Statements; n this type of a construct, if the value of test-expression is true, then the true block of statements will be executed.

Can I write any statement between IF and ELSE?

The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.


1 Answers

I prefer to put the most common path first, and I am a strong believer in nesting reduction so I will break, continue, or return instead of elsing whenever possible. I generally prefer to test against positive conditions, or invert [and name] negative conditions as a positive.

if (condition)
    return;

DoSomething();

I have found that by drastically reducing the usage of else my code is more readable and maintainable and when I do have to use else its almost always an excellent candidate for a more structured switch statement.

like image 172
cfeduke Avatar answered Jan 01 '23 07:01

cfeduke