Ternary Operations
6 Feb 2008 @ 07:38AM

Updated: 25 Jan 2010 @ 07:40AM
A ternary operation is a way to write an if - then -else statement in a much quicker and easier-to-read format. Let's go ahead and wipe out all the if - then - else logic we've created up to this point (it's getting kind of confusing). This would be from the front of the if up to (but not including) the try. Following is an example of a simple ternary operation.

A Ternary Operation

What the hell does that mean? To translate that back to an if - then - else statement, it means this:

Ternary Operation Exploded

To go back to the ternary operation, basically it means that contentString will be appended to. If the name == "Satis", append "Hello Master
", else append "Hello Slave
". That's basically all there is to a ternary operation. It is possible to build ternary operations into one another, kind of like an if - then - else if - else statement like we had before. However, if you're not careful, it's going to be really difficult to read. A single ternary operation like I have above is pretty simple to read once you get the hang of it and takes up MUCH less room than an if - then - else statement. If you have a whole bunch of if - then - else operations to perform the ternary operator can make life very, very easy.
Comments (0)
So... what does a compound ternary operation look like?

A Compound Ternary Operation

This is a pretty simple, but compound, ternary operation. If the name is Satis I greet the master, if the name is Shiny I greet the Mistress, if the Name is Pig or Ox I greet the Grabber, otherwise I greet the slave. This can become as complex as you want it to. Feel free to mix in other variables and comparisons in there, group them with parenthesis and do whatever else you want. Just remember, you have to be able to go back to your code a month (or a year) after you've written it and be able to figure out what it was you were doing. This isn't always as easy as it sounds.

Next we're going to look at another variation of the if - then - else statement, the Switch - Case.
Comments (0)