Search code examples
javacastingreturnmethod-signature

Explicit Casting a return


I'm maintaining a codebase (old, Java 3) written by a vendor that no longer maintains this product.

I am regularly running into things like this:

private boolean doSomething() {
    boolean success = false;
    // do stuff
    if (/*some stuff*/) {
        success = true;
    }
    return success;
}

public void doStuff() {
    boolean ok = (boolean) doSomething();
    if (ok) {
        // do stuff
    }
}

So, Obviously they are trying to determine method success/fail by passing back a boolean indicating status (validation)... I personally think that is bad practice, I'd much rather an exception bubble up to the caller, but that's just me.

The part I'm confused on, why does/did this vendor constantly explicitly cast boolean return values into a boolean? This is redundant and surely causes some overhead during runtime, no? Have I been doing it wrong all this time!? - or is this just some stylistic thing that I should pay no attention to?


Solution

  • It doesn't incur overhead at runtime because casts are there for the compiler. But it is unnecessary. All you need is

    if (doSomething()) {
        // do stuff
    }
    

    It's an idiosyncratic weirdness of somebody who didn't know the language very well and who hasn't read others' code to get an idea of what's good style.