Question

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");
Was it helpful?

Solution

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";

OTHER TIPS

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";

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";

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)];
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top