Alternate format for if…then…else if… using ternary conditional operators


This one is not a big deal – just a reminder to myself of an alternate format that can greatly increase the readability of code in some cases.

Normally, when the blocks are short, I would avoid writing

if (condition) 
{
    true_statement_block;
}
else 
{
    false_statement_block;
}

preferring, instead, the neater look of ternary conditional operators

if (condition)
    ? true_statement_block
    : false_statement_block;

But when the conditions form an if…then…else if… chain, then I like to use

if  (condition_A) ? A_block :
    (condition_B) ? B_block :
    (condition_C) ? C_block :
    ...
    (condition_X) ? X_block :
                    all_false_block;

It’s only a cosmetic thing, but I find that this makes a list of mutually dependent conditions much easier to read and maintain.

Of course, if all the conditions are just testing different states of the same variable, then a switch statement should be used.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s