views:

381

answers:

9

I often find when debugging a program it is convenient, (although arguably bad practice) to insert a return statement inside a block of code. I might try something like this in Java ....

class Test {
        public static void main(String args[]) {
                System.out.println("hello world");
                return;
                System.out.println("i think this line might cause a problem");
        }
}

of course, this would yield the compiler error.

Test.java:7: unreachable statement

I could understand why a warning might be justified as having unused code is bad practice. But I don't understand why this needs to generate an error.

Is this just Java trying to be a Nanny, or is there a good reason to make this a complier error?

A: 

Nanny... close enough I suppose.

It's just the way it is. There's no changing it. It's probably saved me more often than its annoyed me.

Tony Ennis
+18  A: 

Because unreachable code is meaningless, and therefore an error. If you have some unreachable code, you have made a mistake that needs to be fixed.

There is a similar question here: Unreachable code: error or warning?, in which the author says "Personally I strongly feel it should be an error: if the programmer writes a piece of code, it should always be with the intention of actually running it in some scenario." Obviously the language designers of Java agree.

SamStephens
+1 for just getting it right
willcodejavaforfood
_Obviously the language designers of Java agree_ "Language designers of Java" are humans and prone to mistakes too. Personally, I feel that other side in the discussion you refer has much stronger arguments.
Nikita Rybak
I don't think this explains why "meaningless" code is sufficient to justify a compiler error, which would normally be reserved for syntax issues.
Mike
@Mike: compilers don't just check for syntax errors.
BoltClock
@bolt but do any generate errors for issues that aren't related to syntax?
Mike
for final production code, yes. during development, absolutely disagree.
boomhauer
Well this is the thing, isn't it. There's no objective way to say warning or error is better, it comes down to personal opinion. C#'s take is its a warning. My take is that the UI design principle of designing an interface to prevent incorrect input entirely applies to languages either. What does an unreachable statement mean? If its a copy and paste error, we want to be forced to fix it. If the code is intended to be there, it isn't meaningful to the compiler, is therefore there for developers, and can therefore be a comment.
SamStephens
@Mike: Compilers prevent all sorts of things that aren't syntax related - access to uninitialized variables to name a small example.
SamStephens
@Mike: Java spits [a plethora of compile-time errors](http://mindprod.com/jgloss/compileerrormessages.html) that aren't always related to syntax. For instance, forgetting to override abstract methods, attempting to catch exceptions that are never thrown from their try blocks, etc.
BoltClock
SamStephens: It sounds like you've argued against any sort of compiler warning. I don't see why something completely harmless needs to be an error.
Gabe
@Gabe: Because it's not harmless - it's almost certainly a mistake. Either you've put your code in the wrong place, or misunderstood that you've written your statement in such a way that some of it can't be reached. Making this an error prevents incorrect code from being written, and if you want something in an unreachable place in your code for other developers to read (the only audience for unreachable code), use a comment instead.
SamStephens
SamStephens: What qualifies as a compiler warning to you?
Gabe
@Gabe: My personal opinion is that warnings should be used for constructs that should be tidied, but are most likely not indicative of an actual error in coding. Uncalled private methods and unused variables are two I can think of. However, the real answer is that a compiler warning is anything a language designer decides is a warning!
SamStephens
SamStephens: Seeing as how uncalled methods and unused variables are essentially all forms of unreachable code. Why allow some forms and not others? In particular, why disallow such a useful debugging mechanism?
Gabe
@Gabe: Interesting question. For me personally, I still think unreachable code is much more likely to indicate a coding fault than an unused method or variable. However, like I said, it's not something there's a hard and fast answer to, and it's up to the language designer to decide whether warning or error is best for their language.
SamStephens
A: 

It complains about

if (false) {
   System.out.println("Debugging message");
}

And yet it doesn't seem to mind

boolean debug = false;
if (debug) {
  System.out.println("Debugging message");
}

Interesting. StackOverflow knows I'm writing Java code and assigns different colors to "System", "false" and a string literal. Let's see if it recognizes COBOL:

MOVE 0 TO DEBUG-VALUE.
IF DEBUG-VALUE IS EQUAL TO 1 THEN
   DISPLAY DEBUG-MESSAGE UPON CONSOLE.
Mark Lutton
So what does this have to do with the question?
BoltClock
SO.LoadCOBOLColorizer(true);
boomhauer
No, it doesn't complain about if (false). I do it sometimes.
EJP
+3  A: 

It is Nanny. I feel .Net got this one right - it raises a warning for unreachable code, but not an error. It is good to be warned about it, but I see no reason to prevent compilation (especially during debugging sessions where it is nice to throw a return in to bypass some code).

boomhauer
java was designed way earlier, each byte counts at that time, floppy disks were still high tech.
irreputable
For the debug early return, it takes another five seconds to comment out the lines following your early return. A small price to play for the bugs prevented by making unreachable code an error.
SamStephens
it is also easy for the compiler to exclude unreachable code. no reason to force the developer to do so.
boomhauer
A: 

While I think this compiler error is a good thing, there is a way you can work around it. Use a condition you know will be true:

public void myMethod(){

    someCodeHere();

    if(1 < 2) return; // compiler isn't smart enough to complain about this

    moreCodeHere();

}

The compiler is not smart enough to complain about that.

seanizer
The question here is why? Unreachable code is meaningless to the compiler. So the only audience for it is developers. Use a comment.
SamStephens
So I get downvotes because I agree with the way the java guys desgined their compile? Jeez...
seanizer
Just wait 'til I start the 'where to the brackets go' discussion.
Tony Ennis
You get downvotes for not answering the actual question. See SamStephens' comment.
BoltClock
javac can definitely infer that `1<2` is true, and the rest of the method doesn't have to be included in the byte code. the rules of "unreachable statements" must be clear, fixed, and independent of the smartness of compilers.
irreputable
@unicorn so providing an easy workaround is not an answer?
seanizer
Afraid not - question is why it's an error, not how to work around the error.
SamStephens
@Sam with that attitude, you're going to have to downvote 50% of the best answers of this site (and I am not saying that my answer is among those). A big part of answering questions on SO, as in any IT consulting situation, is to identify the real question (or relevant side questions) from a given question.
seanizer
I didn't downvote it...
SamStephens
+3  A: 

One of the goals of compilers is to rule out classes of errors. Some unreachable code is there by accident, it's nice that javac rules out that class of error at compile time.

For every rule that catches erroneous code, someone will want the compiler to accept it because they know what they're doing. That's the penalty of compiler checking, and getting the balance right is one of the tricker points of language design. Even with the strictest checking there's still an infinite number of programs that can be written, so things can't be that bad.

Ricky Clarkson
A: 

It is certainly a good thing to complain the more stringent the compiler is the better, as far as it allows you to do what you need. Usually the small price to pay is to comment the code out, the gain is that when you compile your code works. A general example is Haskell about which people screams until they realize that their test/debugging is main test only and short one. I personally in Java do almost no debugging while being ( in fact on purpose) not attentive.

Jérôme JEAN-CHARLES
+4  A: 

there is no definitive reason why unreachable statements must be not be allowed; other languages allow them without problems. For your specific need, this is the usual trick:

if(true) return;

It looks nonsensical, anyone who reads the code will guess that it must have been done deliberately, not a careless mistake of leaving the rest of statements unreachable.

java has a little bit support for "conditional compilation"

http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.21

if (false) { x=3; }

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

and then write code such as:

if (DEBUG) { x=3; }

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

irreputable
Still don't get why you'd bother with the trick you show. Unreachable code is meaningless to the compiler. So the only audience for it is developers. Use a comment. Although I guess if you're adding a return in temporarily, using your workaround might be fractionally quicker than just putting in a return, and commenting out the following code.
SamStephens
A: 

this is a very interesting question

Viv
Viv, comments don't count as answers. This belongs as a comment to the question itself, or even better, just vote the question up - it serves to indicate that you find the question interesting.
casablanca
@casablanca: His reputation is too low to comment
Daenyth
this is a very interesting response
Mike
these are very interesting comments ;)
boomhauer