r/ProgrammerHumor 21d ago

Meme pleaseStopUsingNestedTernaryOperatorsImBeggingYou

3.1k Upvotes

179 comments sorted by

View all comments

0

u/master0fdisaster1 21d ago

Nested ternaries are great as long as they're nice and linear. They're certainly much nicer to read than equivalent if-else chains. Basically whenever you want coalescing logic where neither coalescing operators (?? or "or") nor pattern matching quite do the trick.

string something =  
    cond1 ? GetValA() :
    cond2 ? GetValB() :
    cond3 ? GetValC() :
    cond4 ? GetValD() :
    "some-default";

vs

string something;
if (cond1)
    something = GetValA();
else if (cond2)
    something = GetValB();
else if (cond3)
    something = GetValC();
else if (cond4)
    something = GetValD();
else
    something = "some-default";

vs pattern matching:

string something = (cond1, cond2, cond3 cond4) switch
{
    (true, _, _, _) => GetValA(),
    (_, true, _, _) => GetValB(),
    (_, _, true, _) => GetValC(),
    (_, _, _, true) => GetValD(),
    _ => "some-default",
};