implementation of "instanceof"

Try using instanceof to test alternately for one interface and then another (on the same object).

Cas :slight_smile:

How do you mean?

My test was

if (obj instanceof Test1) value = VALUE_1;
else if (obj instanceof Test2) value = VALUE_2;
else value = VALUE_DEFAULT;

And that was almost twice as fast as both

value = obj.getValue();

and

int type = obj.getType();
switch (type) {
   case TYPE_1: value = VALUE_1; break;
   case TYPE_2: value = VALUE_2; break;
   default: value = VALUE_DEFAULT;
}

(Those two ran at almost exactly the same speed)

Hmm, I wonder what the speed would be if Test contained a public int type instead of getting it through an accessor…

edit:

Obviously, if you’ve got many classes, the cost of the if ladder would slowly eat up the speed benefit. Not to mention it’s still Bad Code.

Can you run your test with a more hierarchical approach? For instance, Test1 extends Test2 which extends Test3 or Test4 etc. The “homemade” versions shouldnt see a huge performance hit from this, but I wonder if instanceof does. Interesting nevertheless though!

Surely you’re getting into an apples<->oranges comparison there? instanceof means it’s castable to that type, numeric ids just establish that it’s an exact match. A more appropriate comparison would be replacing instanceof with .getClass() == Type.class surely? (which I’d expect to perform the same as the numeric id approach - they’re both going to be an accessor and a comparison).

Yes, it might be apples and oranges, - but if the orange is always tastier, why consider the apple at all? :slight_smile:

http://sinfest.net/comikaze/comics/2004-04-05.gif

;D

:-\

I’ve used instanceof in the past while recursively processing nested hierarchies.

Anything fundamentally wrong with that from a performance point of view? Obviously one needs to be aware of the risk of circular references; that’s a design concern, not a performance one.

That sounds like a good place to use http://en.wikipedia.org/wiki/Composite_pattern

I don’t think that there is any performance difference. Profile your application before thinking about optimizing performance.

Hmmm… but there, the logic for processing the items is held within the items themselves; in fact, I believe the types in question do also use this pattern. What I didn’t make clear is that as I want to have different methods for processing the items in different ways, it seems they also need to apply some reasoning based on the type. This does end up happening in some fairly tight loops as well, so if there was a substantial cost I’d like to know.

[quote]I don’t think that there is any performance difference. Profile your application before thinking about optimizing performance.
[/quote]
Quite. Must get myself better set up with profiling tools… later. For now, I’m certainly not worried about the cost of instanceof… In fact, I guess I was thinking from more of a design perspective after all. There were comments earlier that people seemed to think instanceof would only end up appearing as the result of some other bad design choice; I’m not so sure, and think maybe the pattern I ended up with is a reasonable one. Comments?

[quote=“xinaesthetic,post:31,topic:31897”]
I generally find instanceof to be pretty fragile and a smell that indicates you’ve got something else wrong somewhere. I only use it when forced to (usually by external APIs), but even that is rare. ‘instanceof’ is really not too different from random casts - it might work now, but it’s very easy to break without warning a few refactorings down the road.

In your particular example, I’d probably just make every Item have a child list and remove the CollectionItem interface totally. If you’re worried about the extra overhead you could lazily instantiate the list. Or as already suggested the composite pattern is a good fit here.

Let’s say a have a class of type Vehicle which can be a Car or Ship. How would I create the correct panel for the vehicle? I have a CarPanel and a ShipPanel. The best I came up with is to use instanceof. Suggestions how to do it without instanceof? ???

// create a panel for the given vehicle
Vehicle vehicle = ...
if (vehicle instanceof Car) {
  panel = new CarPanel((Car)vehicle);
}
else if (vehicle instanceof Ship) {
  panel = new ShipPanel((Ship)vehicle);
}
...

What’s wrong with:

panel = vehicle.createPanel();

?

Probably right. I didn’t really think through the properties of that pattern just then (or read the wikipedia page properly). Hardly complicated, I know… :-\

Still, it seems odd that a good solution is to have a high level interface with properties that are only really relevant to a distinct subset of implementations… that said, I don’t see it leading to the same problems with refactoring etc that my method, for example, could. Well, tree structures are hardly novel and I suppose established conventions are probably established with good reason.

Normally you don’t want to create this kind of coupling between the data model classes and views.

Yes, that’s my point! My GUI/View classes are separate from the Model. How can I create a View component without changing the model? The solution I came up with is “instanceof”. Any other ideas?

Ah you want to avoid the dependancy. How about a factory which creates appropriate vehicle/control panel pairs? I assume you’ve already solved the instantiation problem once somewhere when you decide what specific type of Vehicle to create. If the panel is created much later, then you might want a factory object which remembers what it originally created (and maintains a suitable reference to it).

It feels like you’ve lost some information by allowing a Car/Ship to decay to a Vehicle and instanceof is the only way to get it back. I guess you’ve got to either create the right panel when you create the vehicle (before you “lose” the information) or maintain it as extra state (either as a factory object, behind the vehicle interface, or in a higher level class somewhere).

Normally you have this kind of objects in a collection and only want to instanciate the appropriate panel, when you really need to display/edit the object. You even might want to make sure only one panel of a kind exists that can be reused for any object of a type. Or you might want view pooling, if you allow multiple views at a time. Maintaining it as an extra state smells like the “getType()” method already discussed in this thread. I would say, this is a perfect place to use instanceof.

This is what I call object oriented wank. Just write it! It’s no wonder no-one ever seems to finish any games.

Cas :slight_smile: