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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: