5

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");
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431

4 Answers4

10
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";
Steven Wexler
  • 16,589
  • 8
  • 53
  • 80
3

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";
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

You four possible states. A shorter (though not necessarily easier-to-maintain) representation would be

if (A && B) {
    return "W";
} else if (A && !B) {
    return "X";
} else if (!A && B) {
    return "Y";
else return "Z";
Eric J.
  • 147,927
  • 63
  • 340
  • 553
0

I just have to throw this in for fun:

    string Foo(bool A, bool B)
    {
        var labels = new[]{"W", "X", "Y", "Z"};
        return labels[(A ? 0 : 2) + (B ? 0 : 1)];
    }
Scott Jones
  • 2,880
  • 13
  • 19
  • Clever, When I was originally trying to think of better ways to do it I was actually thought about a similar idea but using a switch statement instead of an array :). – Scott Chamberlain May 02 '13 at 22:41