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 you 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 you code ;)
« Home | This article was published on January 20, 2008.

Any thoughts?