Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 The ternary operator: redemption
Index -> General Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Sun Dec 25, 2005 9:51 pm   Post subject: 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:

code:
String foo;

if (bar > baz && bar % 3 == 0) {
   foo = "yada";
} else {
   foo = "wooble";
}


Well, this is pretty easy to convert.

code:
String foo = (bar > baz && bar % 3 == 0) ? "yada" : "wooble";


But... what if we have lots of "else if"?

code:
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:

code:
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.
Sponsor
Sponsor
Sponsor
sponsor
md




PostPosted: Sun Dec 25, 2005 11:28 pm   Post subject: (No subject)

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




PostPosted: Mon Dec 26, 2005 2:19 am   Post subject: (No subject)

This is the beauty of expressions, as opposed to statements.
Display posts from previous:   
   Index -> General Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: