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) 

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 :

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.


Leave a Reply

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

You are commenting using your 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