Quantcast
Channel: Strg+Shift+R
Viewing all articles
Browse latest Browse all 50

How to get rid of "instanceof"

$
0
0
Ok here is the scenario. We get an object x which can be from TypeA, TypeB or whatever. Depending on the classtype of x we want to do different things:

this.makeThings(x);
..

void makeTings(Object x){
if (x instanceof TypeA){
...
}
if (x instanceof TypeB){
...
}
...
}

Ok instead of doing it this way, you should always consider to do it like this to give your code a better structure:

this.makeThings(x);
..

void makeTings(Object x){
System.out.println("you forgot to create a method for type "+x.getClass());
}
void makeTings(TypeA x){
..
}
void makeTings(TypeB x){
..
}
...

Try this and experiment a little bit with it. Then search for "instanceof" in your code and check if it should be modified. This was not tested for performance relevant code. so i'm not sure if its faster or slower then an if-statement to do it this way.

Viewing all articles
Browse latest Browse all 50

Trending Articles