uthomas uthomas - 4 years ago 129
Java Question

Is this some genius thing or simple just bad code?

This is a code snippet I found in an open source Java templating project.

Does anyone have a clue what this construct may be good for?

final public Expression Expression() throws ParseException {
Expression exp;
exp = OrExpression();
{if (true) return exp;}
throw new Error("Missing return statement in function");
}

Answer Source

This is sloppy code. The actual effect is simply return OrExpression();.

There is one excuse that I accept for code like this: There are lots of other methods like it, which follow a similar pattern but are more complex such that the useless bits here are not useless. This is a bit of an extreme example, however.

However, there is almost no excuse for the throw new Error("Missing return statement in function");. The Java compiler will refuse to compile a method whose return type is not void and which has a code path which reaches the end (does not return, throw, or enter an infinite loop). The only reason this would be a good idea is if the intent was to permit incomplete code to compile — i.e. fail at run time rather than compile time so that other parts of the code can be used or tested — but even then applying it to all methods is a bad idea.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download