0

I'm building something that requires some polymorphism utilisation and I was wondering what the flaws in this method of avoiding type comparison might be.

Essentially, I want to place an enum in the base class and then change the value of that enum depending on what the current class is and then use the enum to do type comparison instead.

So for the constructors:

public class Animal{
    private AnimalType animalType; // the enum

    public Animal(AnimalType animalType)
    {
        this.animalType = animalType;
    }

    public getAnimalType()
    {
        return animalType;
    }
}

public class Cat{
    public Cat()
    {
        super(AnimalType.CAT);
    }
}

public class Dog{
    public Dog()
    {
        super(AnimalType.DOG);
    }
}

And then instead of:

 if (dog instanceof Dog)

We do:

 if (dog.getAnimalType() == AnimalType.DOG)

Then would this make any difference to computational speed? What are the flaws that you can think of when doing this? Is there anything vital here that I have personally missed when I came up with this?

I know this isn't perfect for various reasons, but if there are going to be thousands of these comparisons performed per second then shaving off a few microseconds is worth it.

  • 2
    This is probably a little bit faster than `instanceof`, but that's not a good reason to use it unless you've proven (via benchmarks) that it really does make a significant difference to your application. Otherwise, the factors that should matter are maintainability, readability, usability, extensibility, etc. – Radiodef Jul 12 '18 at 17:05
  • Probably won't make any significant difference. But the maintenance task may be slightly different (with an enum, there is an additional unit to maintain) – ernest_k Jul 12 '18 at 17:06
  • The `AnimalType` enum would need to be maintained every time a new subclass of `Animal` is created. – rgettman Jul 12 '18 at 17:06
  • 1
    The performance difference is likely to be negligible, even with thousands of comparisons per second. More to the point is that the two methods are not the same. If `Dog` gets subclassed, do the subclasses get their own enum? Also, one of the fundamental assumptions of inheritance is that the parent class doesn't need to be aware of the child classes. You don't set things up so that you have to make changes to a parent class every time it gets extended. – mypetlion Jul 12 '18 at 17:08
  • See here: https://stackoverflow.com/questions/103564/the-performance-impact-of-using-instanceof-in-java – AutomatedOwl Jul 12 '18 at 17:09
  • Don't make microoptimizations like this based on "computational speed". Write code that's clear to read first. (And note that *any* code that switches based on the subtype/instanceof is usually a poor design. Override methods instead.) – chrylis -cautiouslyoptimistic- Jul 12 '18 at 18:36

0 Answers0