59

Assuming a language with some inherent type safety (e.g., not JavaScript):

Given a method that accepts a SuperType, we know that in most cases wherein we might be tempted to perform type testing to pick an action:

public void DoSomethingTo(SuperType o) {
  if (o isa SubTypeA) {
    o.doSomethingA()
  } else {
    o.doSomethingB();
  }
}

We should usually, if not always, create a single, overridable method on the SuperType and do this:

public void DoSomethingTo(SuperType o) {
  o.doSomething();
}

... wherein each subtype is given its own doSomething() implementation. The rest of our application can then be appropriately ignorant of whether any given SuperType is really a SubTypeA or a SubTypeB.

Wonderful.

But, we're still given is a-like operations in most, if not all, type-safe languages. And that suggests a potential need for explicit type testing.

So, in what situations, if any, should we or must we perform explicit type testing?

Forgive my absent mindedness or lack of creativity. I know I've done it before; but, it was honestly so long ago I can't remember if what I did was good! And in recent memory, I don't think I've encountered a need to test types outside my cowboy JavaScript.

svidgen
  • 14,669
  • @CodesInChaos: IMHO these things can give some evidence that using a "is-a" operator might be the right tool, but I think they don't indicate that we "should or must perform explicit type testing" (as the OP wrote). – Doc Brown Aug 18 '14 at 20:51
  • 2
  • 3
    This is why I like writing C++ and leaving RTTI turned off. When one literally cannot test object types at runtime, it forces the developer to adhere to good OO design with regards to the question being asked here. –  Aug 18 '14 at 21:43
  • One Java example is testing if someList instanceof RandomAccess. – wchargin Aug 19 '14 at 23:11
  • 1
    Stop breaking parametricity :) – Ven Aug 20 '14 at 12:33
  • 1
    Also if the two method calls expect wildly different arguments from the caller o.doSomethingA(int,int,String,float) and o.doSomethingB(bool,int,double,Object) it would be crazy to let both implement a polymorphic method which accepts all 8 parameters and only uses half of them in each implementation... – Falco Aug 20 '14 at 14:48