Question

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?

Was it helpful?

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.

OTHER TIPS

Casts happen at compile time rather than runtime so there'll be non performance impact that I can think of. It's just cruft in the codebase.

You are correct in saying that it could be considered "bad practice" and the return type obviously is boolean.

They most likely had done this to maintain type safety, and it was their own prerogative. Maybe the vendor had a convention that casts every method that had a return type to make sure that they were indeed getting that type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top