Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is instanceof a good practice?

Tags:

java

oop

enums

I have a list of objects which extend from a base class. Now I want to apply a specific operation only on one instance of classes in the list.

Is the use of instanceof a good practice there? Or should I rather differ the objects by eg a custom enum?

abstract class Base;
class Foo extends Base;
class Bar extends Base;

List<Base> bases;

for (Base base : bases) {
  if (base instanceof Bar.class) {
     //execute my custom operation on the base object
     doSomething((Bar) base);
  }
}

If that approach is not that nice in general, how could I do better?

like image 907
membersound Avatar asked Feb 12 '13 21:02

membersound


People also ask

Is it good practice to use Instanceof?

Performance-wise, instanceof is really fast; it's definitely faster than comparing our own type field; it may even be faster than comparing Class with == .

When should you not use Instanceof?

The problem with instanceof is that if you have a large amount of Animal s, you'll end up with a long if-else-if for every one of them. It's hard to maintain and prone to errors where e.g. a new type of Animal is added, but you forget to add it to the if-else-if chain.

What can I use instead of Instanceof in Java?

The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used.

Does Instanceof work for subclasses?

As the name suggests, instanceof in Java is used to check if the specified object is an instance of a class, subclass, or interface.


2 Answers

There does not really seem to be any reason to use instance of here. It might make sense to have the base class default the behavior to doing nothing and override it in extending classes when needed. This way you only override it if needed (I on.y left this as an abstract class to follow with the question its not needed for this example). For example:

abstract class Base{
    public void doSomething(){}
}

public class B0 extends Base{
    @Override
    public void doSomething(){//actually do something}
} 

public class B1 extends Base{}

An example of using this could be something like:

public class SomeOtherClass{
    public void something(List<Base> bases){
         for(Base base:bases)
             base.doSomething();
    }
}
like image 198
John Kane Avatar answered Oct 17 '22 08:10

John Kane


abstract class Base;//abstract function doSomething()
class Foo extends Base;//implements doSomething()
class Bar extends Base;//dito

List<Base> bases;

for (Base base : bases) {
     base.doSomething();
}

To answer your question: it is not a good idea to use instanceof.

like image 40
Burkhard Avatar answered Oct 17 '22 08:10

Burkhard