Nested Ternary operator
I was going through some of my old Java code and found this interesting piece of code. It’s basically alternative way of creating switch structure.
public Object getValueAt(int row, int col) {
Person person = data.get(row);
return
col==0? person.getFirstName()
: col==1? person.getLastName()
: col==2? person.getAge()
: col==3? person.getAddress()
: null;
}
Cons:
- unlike switch, there is no compile time error for duplicated cases
- this is not a standard way of dealing with different values of a variable so you could leave wondering the person that will read your code
Pros:
- more control over branching logic since expressions are used (switch must use constants as case values)
- this is not a standard way of dealing with different values of a variable so you could be seen as hacker in the eyes of the person that will read your code ;)
It’s pretty interesting! I would not use it, though.
I’m currently updating a system and the developer that originally wrote the code had something like this:
var = col==0? person.getFirstName(): col==1? person.getLastName(): col==2? person.getAge(): col==3? person.getAddress(): null;
Everything in one line! That’s almost impossible to read.
This blog entry helped me a lot.
We just need to remember that the machine can read the code anyways, but the average human being needs it more simple and easy to read.
Well, now that I think about it, he had something worse!
$mySort = ($sort==1) ? ‘avg_rating ’.$sortOrder : (($sort==2) ? ‘solved ’.$sortOrder : (($sort==4) ? ‘articletype ’ .$sortOrder : ‘question ’.$sortOrder));
This is a very interesting way of coding a switch, and does allow you to use boolean expressions rather than constants, but you need to realize that this will be much slower than a switch.
Since this is one line, one statement, it will need to process the entire statement before continuing with the execution of the rest of the program.
If efficiency of code is not a high priority or you really need to user a boolean expression for a switch then by all means use the example.
Good example though.
Any thoughts?