Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapsing if statements when more than one condition is anded

Tags:

c#

Is there any way to collapse this into one if condition, or just one return statement?

     public bool SomethingEnabled
     {
            if (!condition1)
            {
                return false;
            }

            return condition2
                && (condition3 || !condition4);
      }
like image 782
gurunakka kamelseh Avatar asked Jun 05 '11 04:06

gurunakka kamelseh


4 Answers

This is equivalent:

public bool SomethingEnabled
{
    return condition1 && condition2 && (condition3 || !condition4);
}

but in the interest of readability and maintainability, I would strongly caution against writing code that's too clever.

like image 59
Matt Ball Avatar answered Nov 01 '22 23:11

Matt Ball


return condition1 && condition2 && (condition3 || !condition4);
like image 30
trutheality Avatar answered Nov 01 '22 22:11

trutheality


return condition1 && (condition2 && (condition3 || !condition4));

The first condition is to return false if condition1 is false. The condition will evaluate to false altogether if condition1 is false. If it's true, it evaluates to whatever the rest does.

like image 2
Aleadam Avatar answered Nov 01 '22 22:11

Aleadam


Better names and small functions would help:

public bool SomethingEnabled
{
   if (IsInvalid) return false;

   return IsInReadyState && IsInOtherState;
}

public bool IsInvalid
{
   return !condition1;
}

public bool IsInReadyState
{
   return condition3 || !condition4;
}

public bool IsInOtherState
{
   return condition2;
}
like image 1
Ritch Melton Avatar answered Nov 02 '22 00:11

Ritch Melton