I have a data model that includes a big list (array) of heterogeneous items. There are only 2-3 different kinds of item, each kind inheriting from a base class. Using classic examples, let's say the base class is Vehicle, and the subclasses are Car, Train, and Plane.
I have a larger owning model/controller that wants to operate on this ordered list of Vehicles, and while some of the operations are shared (and are in the base class and overridden in subclasses), many of the operations are specific to only one of the kinds of items.
So I end up with a lot of code that looks like this:
for (Vehicle * vehicle in vehicles) {
if (![vehicle isKindOfClass:[Car class]]) {
continue;
}
Car * car = (Car *)vehicle;
// Do stuff only with "car".
}
So I've got lots of -isKindOfClass: everywhere and lots of casting the base class to the subclass. This all works, of course, but there seems like enough "code smell" to make me think there might be a more elegant way of either writing this code, or designing my object model.
Thoughts? Thanks.
I guess the usual polymorphic pattern would be to push the body of the loop out into the classes in question, so your loop turns into
for (Vehicle * vehicle in vehicles) {
[vehicle doSubclassSpecificThing];
}
The question then is how to share the common part of the loop body. It's possible you could break it into a series of chunks:
for (Vehicle * vehicle in vehicles) {
/* common code */
[vehicle doThingy];
/* further common code */
[vehicle doOtherThingy];
}
Or you could have -doSubclassSpecificThing be required to call [super doSubclassSpecificThing] first, and put the common part in the base class if it all comes first.
Basically, it sounds like your loop body has a number of things going on in it. If you extract each one to a method you can choose which pieces to share or override, and your loop body becomes a very high level description of what to do instead of the details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With