Is using the instanceof keyword against the essence of object oriented programming?
I mean is it a bad programming practice?
I read somewhere that using instanceof keyword means that the design may not be that good. Any better workaround?
Is using the instanceof keyword against the essence of object oriented programming ? I
Share
Generally speaking yes. It’s best to keep all code that depends on being a specific class within that class, and using
instanceofgenerally means that you’ve put some code outside that class.Look at this very simple example:
Ideally, we’d like all of the behaviour that’s specific to dogs to be contained in the Dog class, rather than spread around our program. We can change that by rewriting our program like this:
We’ve specified that an
Animalhas to have aspeakmethod. NowSomeOtherClassdoesn’t need to know the particular details of each type of animal – it can hand that off to the subclass ofAnimal.