0

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?

adskuser
  • 19
  • 4
  • Please explain your problem in further detail. Why do you need to cast the objects to their specific type? Could that logic not be implemented in the specific types, `Cat` and `Dog` themselves? – Seeta Somagani Jun 05 '13 at 23:28
  • Thanks for the edit, but my question still stands. Is that functionality not of the type where you can add, say, an abstract method `makeSound()` that each of `Cat` and `Dog` can implement on their own? – Seeta Somagani Jun 05 '13 at 23:58
  • Is your issue with the if conditions or the casts? From the information you've given, you will need the casts. You could maybe try and replace the if conditions with a switch statement. – Seeta Somagani Jun 06 '13 at 00:15
  • No, `Dog` can do some things that `Cat` can never do. Though you are right, in this example it makes sense to have an abstract method. – adskuser Jun 06 '13 at 00:17

1 Answers1

0

If you can improve your Animal class to better capture the expected behavior of this type of objects, that should be the first thing to do.

Other than that, there's not much I can suggest from the given information.

Seeta Somagani
  • 776
  • 1
  • 11
  • 31