Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Operator use to increase variable

Is it a good practice to use the ternary operator for this:

answersCounter = answer.length != 0 ? ++answersCounter : answersCounter;

This is a question that I always asked myself as it happens quite often. Or, is it better to use a normal if statement? For me, this looks much cleaner in one line.

like image 769
FraK Avatar asked Jun 13 '16 23:06

FraK


1 Answers

This is just opinion, but I think that writing the increment like you have it is somewhat poor style.

Assigning a variable to a pre-incremented version of itself is a little bit confusing. To me, the best code is the clearest (excepting nods to optimization where necessary), and sometimes brevity leads to clarity and sometimes it does not (see anything written in Perl... I kid, sorta).

Have you ever had the programming trick question of:

int i = 5;
i += i++ + i;

Or something similar? And you think to yourself who would ever need to know how that works out since when would you ever assign a variable to the pre/post increment version of itself? I mean, you would never ever see that in real code, right?

Well, you just provided an example. And while it is parseable, it is not idiomatic and not clearer than a straight forward if.

E.g.

if (answer.length != 0) answersCounter++;

Of course, some people don't like if statements with out braces, and don't like braces without newlines, which is probably how you ended up with the ternary. Something with the coding style needs to be re-evaluated though if it is resulting in (subjectively) worse code to avoid a few carriage returns.

Again, this is opinion only, and certainly not a rule.

like image 118
Trevor Freeman Avatar answered Sep 23 '22 15:09

Trevor Freeman