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);
}
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.
return condition1 && condition2 && (condition3 || !condition4);
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With