0

Those of us who worship at the Church/Mosque/Synagogue/etc. of Object-Oriented design often spit in the face of instanceof. My question is whether it is permissible, and moreover, preferable in the given context where you want to give another developer the ability to pass a variadic mixture of expected types to one entry point function (foo), to make their code terser/simpler (aka Facade):

   // a lightweight demo of the integral idea behind the Facade DP...

public void foo(Object... objs){

 for(Object o : objs){
        if(o instanceof Integer) bar((Integer)o); 
        else if(o instanceof MyCustomType) bar((MyCustomType)o); 
        else if(o instanceof String) bar((String)o);
        //else{...} ignore? report exception?
    }

}


private void bar(int i){
  System.out.println("integer overload invoked");

}

private void bar(String s){
  System.out.println("String overload invoked");

}

private void bar(MyCustomType instance){
  System.out.println("MyCustomType overload invoked");

}

Yes this is arguably a bit fugly, but assuming no polymorphism between the three types (Integer, String, MyCustomType) other than being seen as Objects, is it not easier to use instanceof as opposed to writing auxillary wrapper objects for each expected type:

private abstract class Wrapper<T>{

  abstract void meth(T t);
}

private class StringWrapper extends Wrapper<String>{

   @Override
   void meth(String s){

       System.out.println("String overload invoked");
   }
}


// etc...

This is better design in terms of OO sure, but should you always use the wrapper approach?

Or may there even be a downside to this approach in terms of efficiency or memory? And seeing as the use of instanceof is confined to invoking some methods hidden by the Facade could you even go so far as to recommend this style? After all, there is limited reuse scope for wrapper classes in this scenario anyway as they have purely parent class scope.

What are some pros and cons of both approaches in this specific context?

Darius
  • 5,180
  • 5
  • 47
  • 62
  • I'm not exactly a priest of the OO church, but I'd usually prefer the instanceof version. However, in my own work I usually find that the need to do any of this is a code smell and suggests redesign. I'm not saying that there are cases where this is justified, I'm just saying that often you can find a better solution if you look hard enough. – Jochen Dec 12 '12 at 14:27
  • That seems to be the common viewpoint, that its the product of personal taste and application context. Java has always been an OO language, so presumably the designers deemed that instanceof would still be a useful operator. In essence, the two approaches are not therefore mutually exclusive one garners? – Darius Dec 12 '12 at 15:12
  • I would certainly say that they are not mutually exclusive. As you said, if you make a rational and informed decision for either, it will most likely not be "wrong". – Jochen Dec 12 '12 at 15:35

0 Answers0