I have a function that is like the following
string Foo(bool A, bool B)
{
if(A)
{
if(B)
{
return "W";
}
else
{
return "X";
}
}
else
{
if(B)
{
return "Y";
}
else
{
return "Z";
}
}
}
That double nesting just feels wrong to me. Is there a better way to implement this pattern?
Thank you everyone for helping, I end up going with the trinary route. It helped turn this:
if (female)
{
if (nutered)
{
destRow["TargetSex"] = "FS";
}
else
{
destRow["TargetSex"] = "F";
}
}
else
{
if (nutered)
{
destRow["TargetSex"] = "MN";
}
else
{
destRow["TargetSex"] = "M";
}
}
in to this
destRow["TargetSex"] = female ? (nutered ? "FS" : "F")
: (nutered ? "MN" : "M");
To combine the logic of nested ifs into a single if statement we use C#'s logical AND operator ( && ). This operator combines two Boolean expressions into a single true/false value. When the value on its left and the value on its right are both true , && returns true as well.
Alternatives to nested IF in Excel To test multiple conditions and return different values based on the results of those tests, you can use the CHOOSE function instead of nested IFs. Build a reference table and a use VLOOKUP with approximate match as shown in this example: VLOOKUP instead of nested IF in Excel.
A function should do only one thing, if you have nested if like this your function is certainly doing more than one thing. So that means, each if/else if/else block should then be in its own function. This solved the nested if problem. And the extracted function should be given a descriptive name of what it does.
Why This is Bad. Deeply nested conditionals make it just about impossible to tell what code will run, or when. The big problem with nested conditionals is that they muddy up code's control flow: in other words, they make it just about impossible to tell what code will run, or when.
if (A)
{
return B ? "W" : "X";
}
return B ? "Y" : "Z";
Or even more terse:
return A ? (B ? "W" : "X")
: (B ? "Y" : "Z");
If your going for exclusively unnested conditions:
if (A && B) return "W";
if (A && !B) return "X";
return B ? "Y" : "Z";
Logically, no. You have 4 distinct conditions for two variables.
You can make the code more concise, though:
string Foo(bool A, bool B)
{
return A ?
B ? "W" : "X"
:
B ? "Y" : "Z";
}
Or if you're feeling particularly evil, put it on one line with no parens!:
return A?B?"W":"X":B?"Y":"Z";
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