Submission: switch (...) instanceof feature

Jeroen van Maanen jeroen at
Tue Mar 31 02:20:57 PDT 2009

Gabriel Belingueres schreef:
> IMO I'm against this.
> First, it is against current best practices for the design of
> object-oriented software to make easier to code something with a case
> statement on types/classes.

I read this as: the 'current best practices [of] design' say that if I want to write code that is easy to reuse because it doesn't make any a priori assumptions about the types of the objects it deal with, then the code *should* be hard to read. If that is a correct translation of the directive, then I would like to know the resulting benefits of following the directive before accepting it. Please provide a reference to an article that discusses the pro's and con's of this.

This proposal is attempting to deal with a real every day problem with writing reusable code and that is: how do you deal with a lack of compile time knowledge and uncooperative objects. (The logging API doesn't know the type of the object logged and the object logged doesn't know that is being logged, so it doesn't provide logging assistance methods). Somebody said that I would be easy and neat to code this kind of thing using a continuations API. What would that look like?

> Second:
>  void log(Object object) {
>    switch (object) instanceof {
>    case String:
>      logger.debug("'" + object + "'");
>    case Date:
>      logger.debug(object.getTime());
>    case void:
>      logger.debug("null");
>    default:
>      logger.debug("<" + object.toString() + ">");
>    }
>  }
> It think it is clearer (when possible) writing it with several
> overloaded methods and double dispatching.

I never found a way to get my code that shows me the contents of collections and arrays and that distinguishes between strings and object representations to work without instanceof or isInstance.

> Third:
>    } catch (Exception exception) {
>      switch (exception.getCause()) instanceof {
>      case ParseException:
>        log.warn("Could not get status for '" + id + ": " +
> exception.getCause());
>      default:
>        log.warn("Could not get status for '" + id + ", exception);
>      }
> }
> in the case you intentionally left out the break statement, then the
> switch statement is not any clearer than doing an if.
> in the case that you wanted the break statement on the ParseException
> case, it is even clearer to use two catch blocks (one for
> ParseException and other for Throwable.

Two catch bocks won't work. The distinction is on the *cause* of the exception, not the exception itself.

> [...]

More information about the coin-dev mailing list