Layne, this might not be what you meant to say, but
"just use a cast and check if the result is not null" almost reads as if casting an OrderA object to OrderB type will result in a null value. It will of course throw an exception.
I agree with you that adding different flavours of Order to a Vector (well, preferably a List implementation from the Collections framework such as ArrayList) is a very OO thing to do. Michael, too, is absolutely right when he says that you don't want nonsensical state in the Order base class.
However, the need for instanceof and casts is a bit of a code smell. You're using them to do different things depending on the precise type of the Order. This is, of course, exactly what
polymorphism was designed to handle for you!
I'll suggest two ways you can leverage polymorphism to address your problem. I'm not saying they're "better" than the instanceof solution discussed so far. Sometimes they are, sometimes they aren't; I don't know enough about your problem to make that decision for you.
I will assume that type A orders have some extra attribute called FooBar.
The first way would be decide that an Order is something that might or might not have a FooBar attribute, which is undeniably true. Correspondingly, an Order should have a getter that might or might not return a value.
Although there is this getter in Order for FooBar, only OrderA objects contain any actual state corresponding to this attribute. In your JSP you can check the value returned for fooBar to decide if you need to display that attribute or not.
The second alternative is in some ways more elegant, but might be less practical in a JSP context. It uses double dispatch to avoid any
testing of object types or return values.
The cute thing is that the usual
Java method overloading rules ensure that OrderDisplay will display order details as accurately as it can. OrderA has its own display method. In the code shown above, OrderB will use the generic Order display code. If there's something specific you want to display for OrderB objects, you just add a display(OrderB order) method without changing any of the actual Order classes.
This double dispatch method is a way to take a specific concern (displaying, in this case) that would otherwise be spread over all the classes in a hierarchy, and concentrate it all in a single class. It is most useful for concerns which are not really part of the classes' responsibility. For example, the purpose of an Order is to encapsulate order state. It shouldn't have to worry about how it is being displayed, how it is being fulfilled, and so forth.
Does this help?
- Peter