Saturday, April 26, 2008

Using the ternary operator

There are many scenarios i which developers have to narrow to a specific type based on a super type which is passed. The following code is what i have normally observed
Lets assume we have the following hierarchy

Class A {
...
}
Class B extends A {
...
...
}
Class C extends A{
...
...
}
Now someMethod takes A as a parameter and needs to narrow it to a specific type B or C
public void someMethod(A a){
A a1=null;
if(a instanceof B) {
a1=new B();
}
else{
a1=new C();
}
.....
//other stuff here
}
A better approach for brevity sake would be use the ternary operator
A a1= a instanceof B ? new B() : new C() ;
This reduces 4 lines to 1 which is some improvement.

The emperor and me beaching

The Devil next door

Kaiser The Emperor