
-----------------------------------
wtd
Sun Dec 25, 2005 9:51 pm

The ternary operator: redemption
-----------------------------------
Is the ternary operator just an ugly piece of legacy syntax, or can it be useful, and even elegant?

Imagine something like:

String foo;

if (bar > baz && bar % 3 == 0) {
   foo = "yada";
} else {
   foo = "wooble";
}

Well, this is pretty easy to convert.

String foo = (bar > baz && bar % 3 == 0) ? "yada" : "wooble";

But... what if we have lots of "else if"?

String foo;

if (bar > baz && bar % 3 == 0) {
   foo = "yada";
} else if (bar % 4 == 0) {
   foo = "wooble";
} else if (baz % 5) {
   foo = "ninja";
}

This can become:

String foo =
   (bar > baz && bar % 3 == 0) ? "yada"   :
   (bar % 4 == 0)              ? "wooble" :
   (baz % 5 == 0)              ? "ninja"  :
                                 "yada yada";

So, what are the benefits to this?

The benefit is really just one I've talked about a million times before.  I only write "foo =" once.  This makes it much easier down the read to change the name of the variable, or if you prefer "refactor" the code.

-----------------------------------
md
Sun Dec 25, 2005 11:28 pm


-----------------------------------
I've never used the ternary operator before... but that last example is way nicer then the equivalent if statement... I didn't ever even think of doing it like that before... nice!

-----------------------------------
wtd
Mon Dec 26, 2005 2:19 am


-----------------------------------
This is the beauty of expressions, as opposed to statements.
