Let's say we have something like this:

public abstract class MyClass {
    //Stuff in here
}

public class MyClassA extends MyClass {

    private String thingie; //Along with getter/setters, of course
    //Other stuff
}

public class MyClassB extends MyClass {

    private List<Integer> thingies; //Again, getters and setters to go with
    //Other stuff
}

Let's assume we have any number of classes that extend MyClass, each with it's own instance variable of a different type, although some may have the same type. This is an unfortunate necessity. Now, let's assume we have a Collection of MyClass. We have a collection filled with any number of child classes, each with an object contained within. Let's say I need to iterate over this Collection, retrieve said object from any number of elements, and perform actions upon it, store it, manipulate it, send it elsewhere, etc. These objects have nothing in common aside from extending Object.

I might be able to simply delegate these actions into the MyClass children themselves, use a visitor, etc, but this likely isn't feasible as these actions may be dependent upon other MyClass children in the Collection. A single MyClass child likely won't dictate the action to be taken all by itself, or even any single Collection of MyClass. Some of these actions may be cumulative and dependent upon a number of other potential cumulative factors.

Is there any "good" way to handle this, or am I just going to be cursed to the hell of ugly typechecking conditionals or something similar? I considered using Generics in MyClass and using concrete types on all of the children. This could simplify the retrieval of objects, but would still necessitate a large conditional block.

1

There are 1 best solutions below

3
On

You discarded in your question the "good" way of doing it. Generics will not help in this case. Yes, you are going to be cursed to a nasty place for the ugly use of type checking. You can disguise the type checking using a common instance member called, say, category and its corresponding accessor getCategory defined in MyClass. And them do a switch if you can (instead of multiple ifs) on getCategory(). However, the people who will condemn you could dislike ifs and switches no matter if they are checking for types or not. And they could also be smart and understand what you are trying to do. Anything but

for(MyClass e: collection )
    e.doYourAction();

is "bad".

Now, for software that seems to have no specification at all, you could be pardoned.