Instanceof issues

I’ve been discussing with a friend about how to avoid using instanceof.
The most obvious answer is to have a proper design in the first place.
However the previous argument on these forums over instanceof was about why Java needs it and not how to overcome the issue through proper design.

I’ve pretty much tried to come up with a paper solution on how to remove dependency on instanceof, one of the assumptions is that both classes (Board and MagicUser) absolutely must know the class type of the BoardPiece.

http://members.optusnet.com.au/ksaho/designs/avoidInstanceof.png

Can someone offer an alternative on how to avoid instanceof in this situation.

SImple. Im goign t odo this in java5 cause ist cleanest but simairlt echniques work for earleir kidsn of Java

Boardpiece, which i assume is an Interface (but coudl also be an abstract class) defines the following:

enum PIECE_TYPE {PAWN, KNIGHT, MAGIC_KNIGHT}

public PIECE_TYPE getPieceType();

Each peice type then over-rides getPieceType to return the apporpriate enum.

If BoardPiece is an abstract class then getPieceType() is defined as an abstract method.

If you arent udner Java 5, you use int and public static final int constants ( or Josh Bloch’s “secure enumeration” pattern) instead of the enum.

JK

Edit: Its shoudl be noted that this really doenst solve the REAL problem. The user is still likely going to start doing switches on the returned peice type which is almost always wrong. It usually indicates incorrect object design.

Nice.
Thanks.

Design has always been an issue. I would like to know when Java will incorporate a fully functional OO design so that things like instanceof are deprecated.
I’ve avoided using instanceof for a long time now however it still must be used when overriding the equals method.

I don’t understand why you think inststanceof is so bad. What do you mean by ‘fully functional OO design’?

The instanceof operator is useful in several ‘OO’ design scenarios. I use it extensively in an action validation system I implemented in my current project. I use it there because it makes sense. I’m not using it in any other systems in my project. Does that mean my project, or at least that particular system, is poorly designed? Does that mean my project is not ‘full OO’ (whatever that means)? Not even.

I’ve heard people say that using instanceof is indicative of a bad design, but that’s rubbish. It’s like the goto argument in C. Abusing the instanceof operator is bad design. And by abuse I mean designing your code around it, or using it when where it doesn’t make sense to. In those cases where it does make sense it is an elegant solution. I’ll be happy to give you an example of what I mean.

For me the only part of the program where I should not use instanceof is in tight-loops, because it quite a heavy operations. Everywhere else may be perfectly justified to use instanceof and should not be discarded as non-OO or not-fully-functional-OO (whatever that means…!). It’s just one of the tools that Java allows you to use, one should not avoid it just for the sake of it.

surely one preferes compile time checking over runtime checking, however deprecating instanceof is a whole other step. sure you can stuff and should stuff instanceof as low/early in your code as possible I can’t see going without it.

“instanceof” is a tool like the rest of java. Use it where it makes sense. Deprecating would be a mistake. Implementing the equals() method would be very annoying without it :slight_smile:

However, surely the real solution is not to check the type of the object externally at all. Wherever you decide you need to check the type externally and perform some type specific functionality, put that functionality where it actually belongs - in the class in question (i.e. type specific functionality for maintainability should be kept with the specific type :))

Poor example:

Interface Fruit. Two implementations Apple and Orange. Using instanceof (or any other external type check) you might have done:


public void eatSomeFruit(Fruit fruit) {
if (myFruit instanceOf  Apple) {
    System.out.println("Yum Yum!");
} else if (myFruit instanceof Orange) {
    System.out.println("Yucky!");
}

The response is specific to the type so put it where it should be, with the type. So we’d add eat() to the interface Fruit and implement appropriately in the types.


public interface Fruit {
    public void eat();
}

public class Apple implements Fruit {
   public void eat() {
      System.out.println("Yum Yum!");
   }
}

public class Orange implements Fruit {
   public void eat() {
      System.out.prinltn("Yucky!");
   }
}

and finally our icky instanceof utility fruit eating method becomes:


public void eatSomeFruit(Fruit fruit) {
    fruit.eat();
}

HTH,

Kev

When I was doing my entity framework and some AI stuff, i was worried about instanceof stuff, and changed to using getType() stuff, and I noticed that in a very crap microbenchmark, instanceof was 2 - 3 times FASTER than a method call…

http://www.java-gaming.org/forums/index.php?topic=5359.0

Alot of usefull advice is in that thread

DP

I used to be under the impression that instanceof was slow. Then I saw the source for SEDA a few years ago (a high performance, non-blocking, networking library - pre NIO stuff). Somewhere in the codebase there was an even handling mechanism which used instanceof to route events. I was surprised to see it at first. Now I know it’s not so bad.

instanceof will never be remnoved because it has legitimate uses. You can do the same things with reflection ops but instnceof is easier and produces cleaner lookign code for the msot commonc ases such information is necessary.

Those uses, btw, are typically in very special cases involving run-time loaded code where the class hirearchy is not known apriori.

Really, instanceof isn;t the issue.

switch is the issue. 98% of the time when you see a swtich statement it means a crew up in the OO design as all such code-switchign decisions aught to be handled by your inegritance structure.

There are expections ther too, though. Packet handling woudl be seriously annoying without switch. Similarly some other linds of data parsing are really adied by it (like writing recursive descent parsers.)

Thanks for the information.
I read Bla^3 rant about instanceof being there due to Java not being a full OO design so I had taken his position on instanceof and further advanced it as being evil.

Things are seldom as simple or cut and dried as a good rant makes them out to be,

The work I do in my day job depends HIGHLY on instanceof for this exact reason. We would have to change thousands of lines of code if it was removed.

FWIW there are a few key areas of the SGS that depend on instanceof for similar reasons :slight_smile:

Unfortunately, telling bad programmers that will only result in them doing the same thing with an else if ladder instead, then spending the rest of their careers fearing the “horrible switch statement”.

What really NEEDS to be removed, however, is the do {…} while statement. It’s almost as evil as come from.

I used do{…}while() like 2 times in 6 years. It’s just:

boolean first = true;
while(first || <original condition>)
{
   first = false;
   <original code>;
}

And what’s so extremly evil about it? It has its uses, once every 3 years…

do…while is only good if you want to run the code inside the loop one time before checking the condition. can’t think of any useful examples though … o_O;;

Usually where you have special case code for the zero case, so that you know the loop will run at least once but don’t want to redundantly repeat the test on that first iteration.

I use it in my 4k game loop.

do {
game initialization

main game loop

game over
} while (wants to play again);