FAQ
overflow

Great Answers to
Questions About Everything

QUESTION

I often like to do things like this:

return (aCondition == aThing)
        ? someLongExpression.getAThing()
        : somethingElse;

Is this practice considered more or less readable than using a simple if/else block, like this:

if (aCondition == aThing)
    return someLongExpression.getAThing();
else
    return somethingElse;

{ asked by Jake King }

ANSWER

I find that the ternary operator (or conditional operator, as it's officially known in C#) can be used for improvement or abused horribly. So, employing a stock answer to many programming questions like this, it depends.

I generally think that fewer lines of code, if done right, minimizes the points of failure that could occur. One return statement in one line of code versus two returns embedded in an if-else-control block.

Now, without more context around your example, it's hard to say whether you're using it in its intended spirit or not. I'm inclined to say "yes" it's good and is more readable over the alternative given what I see.

{ answered by Jesse C. Slicer }
Tweet