When is type testing OK?

Posted by svidgen on Programmers See other posts from Programmers or by svidgen
Published on 2014-08-18T19:02:41Z Indexed on 2014/08/18 22:31 UTC
Read the original article Hit count: 423

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 seems 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.

© Programmers or respective owner

Related posts about type-systems

Related posts about type-checking