Why Java is Not My Favorite Language — Reason #39

Java is early bound. Early binding is an optimization which, like most other optimizations, it is almost always premature. This particular premature optimization causes significant amounts of superfluous code. For example, assume that we the following API for writing to a log file.

class Logger
    public void log(Object obj) {...}
    public void log(Throwable e) {...}

log(Object) writes the results of obj.toString() to the log file and log(Throwable) writes e.getMessage() and a backtrace. Now I want to wrap this API in my class so that when something goes wrong I can do some clean up, in addition to logging the fact that something went wrong. Sometimes my code detects problems by catching an exception and other times by explicitly checking for certain conditions. So I write the following method and call it every time I detect a problem, either with the exception or with a string that describes the detected problem.

private void handleError(Object description)
    // do clean up

Because Java is early bound this handlerError() method always calls Logger.log(Object) even if description is actually a Throwable, which means I never get the backtrace in my log file. To make this work correctly I have to write multiple version of the handlerError() method or add some instanceof checking and casting just to inform the compiler of the object type. Either way that extra code adds no value to my application and I hate writing code that adds no value to my application. Unfortunately, I feel like I end up doing that a lot in Java.

Comments 1