I'm trying to refactor parts of a large codebase and am at a point where the code resembles -
abstract class Animal {
String type;
}
class Dog extends Animal {
public Dog() { type = "DOG"; }
}
class Cat extends Animal {
public Cat() { type = "CAT"; }
}
Now there are a lot of methods all over the codebase that take List< Animal > as input, so I don't want to disturb those interfaces. In many of those methods, the list is typically iterated over and some processing is done depending on the "type" attribute of the Animal object for every object in the list. For this I have to do ugly downcasts from Animal to Cat or Dog. Example:
class Processor {
public void process(List<Animal> animals) {
for(Animal animal: animals) {
if(animal instanceof Dog) { // or if type.equals("DOG")
Dog dog = (Dog) animal;
dog.bark();
} else if {....}
}
}
}
I was wondering if there's any other way to do it. Any thoughts?