• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

good examples of unreachable code?

 
nick woodward
Ranch Hand
Posts: 370
11
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are there any good resources or example of more complex or tricky code that is/is not unreachable? i mean i understand that code after a return statement is unreachable, but is there anything more like this:



Also, I assume that anything that has to be evaluated to effect control flow cannot cause a statement to be unreachable, because the compiler cannot know the result.

I'm still having a bit of a google to find some more, but does that sound like I've understood correctly? I've just dropped a few marks on mocks to questions involving unreachable code... and wouldn't mind getting it sorted!

Thanks,

Nick
 
Ramya Subraamanian
Ranch Hand
Posts: 178
17
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have come across these..




 
nick woodward
Ranch Hand
Posts: 370
11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ramya Subraamanian wrote:I have come across these..







while(false){}

really? oh yeah, so it is....that's a good one! would definitely have me pulling my hair out in an exam! thanks!

the others i would've got i reckon

have you passed your exam? i'll post some more when/if i find any good ones


regards,
nick
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nick woodward wrote:Also, I assume that anything that has to be evaluated to effect control flow cannot cause a statement to be unreachable, because the compiler cannot know the result.

An "unreachable code" error is a compiler error. So anything that the compiler can evaluate and determine at compile time could result in such an error. Let's have a look at some few basic simple examples:But if the result is not known at compile-time, the compiler can't know it at compile-time and thus can't give a compiler error. Easy peasy! So a small change (adding 2 characters ;j at the appropriate location) to the go4 method will result in a successful compilationBut it's also very easy to deceive the compiler and that's even more fun Again using an adjusted version of the go4 method

nick woodward wrote:Are there any good resources or example of more complex or tricky code that is/is not unreachable?

Luckily for you, the "unreachable code" topic is one of the more popular ones in this forum. So using the search function you'll find plenty of topics about "unreachable code". Here is a list which could probably be added to my certification book
  • return value for method.
  • Confused point about infinite loop
  • continue and break in a loop would generate compilation error?
  • Which of these is unreachable code?
  • Unreachable Code
  • Which is the first line to cause error?
  • Maybe "unreachable code" should be "dead code" in page 70, (Java OCA 8 Programmer I Study Guide)
  • Throwing a second exception question
  • System.exit() and unreachable code

  • I think you know what to do this weekend

    Hope it helps!
    Kind regards,
    Roel
     
    Ramya Subraamanian
    Ranch Hand
    Posts: 178
    17
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    the others i would've got i reckon


    way to go ....

    have you passed your exam?


    No, I havent taken the exam. Yet to finalize on the date...

    i'll post some more when/if i find any good ones


    Sure, it would be useful for the exam
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ramya Subraamanian wrote:I have come across these..

    Have a cow for these nice examples of "unreachable code". Most of them are not mentioned in my post, so our posts are really complementary
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ramya Subraamanian wrote:
    i'll post some more when/if i find any good ones


    Sure, it would be useful for the exam

    Then it would definitely be useful to check the links I provided in my first post in this topic
     
    Ramya Subraamanian
    Ranch Hand
    Posts: 178
    17
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I went through the threads. This was interesting.This snippet below wouldnt compile because the compiler doesnt know that i<1 (like (while<true)) would result in a endless loop as i is not a compile time constant.so compiler asks for the return statement.

    In this thread(last post), you are saying that a code snippet doesnt compile. line 1 and line 2 in my code below compiles ,but it is dead code. Compiler doesnt complain line 3 is dead code, but it does compile. and I thought if(false) is similar to having if(<compile time constant boolean value>).What am I missing here...or was it some other scenario.



     
    Joe Bishara
    Ranch Hand
    Posts: 175
    17
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ramya Subraamanian wrote:What am I missing here...or was it some other scenario.

    Roel provides an explanation in this thread (the last post)

    The JLS also provides an explanation

    The following statement results in a compile-time error:

    while (false) { x=3; }

    because the statement x=3; is not reachable; but the superficially similar case:

    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.
     
    nick woodward
    Ranch Hand
    Posts: 370
    11
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    really like that explanation of why if statements allow unreachable-looking code. thanks, will definitely help me remember why.

    also, to add to that while(false) explanation - i don't think that x=3 is technically the problem.
    while(false){} results in a compile-time error due to unreachable code, even though there is no code that is unreachable.

    oh and reading that first link now Roel - thanks. some of those examples with infinite loops and no return types are 'interesting' to say the least.

    so an infinite loop negates the need for a return statement? (as long as the compiler knows the loop is infinite due to a literal or constant). is there any design reason for this? seems like a strange allowance to make.


     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ramya Subraamanian wrote:This snippet below wouldnt compile because the compiler doesnt know that i<1 (like (while<true)) would result in a endless loop as i is not a compile time constant.so compiler asks for the return statement.

    That's indeed true! i is not a compile-time constant, so the compiler can't know 0<1 will always be true (in this case) and therefore requires the return statement to be present.

    Ramya Subraamanian wrote:line 1 and line 2 in my code below compiles ,but it is dead code. Compiler doesnt complain line 3 is dead code, but it does compile. and I thought if(false) is similar to having if(<compile time constant boolean value>).What am I missing here...or was it some other scenario.

    In short: Java does allow unreachable code caused by if statements, even if you don't use a variable but a constant. I've given a more detailed explanation in this post (included a possible scenario where this could be useful).
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    nick woodward wrote:also, to add to that while(false) explanation - i don't think that x=3 is technically the problem.
    while(false){} results in a compile-time error due to unreachable code, even though there is no code that is unreachable.

    There's a code block and the code block is unreachable. Similar if you added nothing but an empty statement (;), that line would also not compile because the empty statement is unreachable. It's so simple and consistent These all don't compile:


    nick woodward wrote:so an infinite loop negates the need for a return statement? (as long as the compiler knows the loop is infinite due to a literal or constant). is there any design reason for this? seems like a strange allowance to make.

    Why bother about a return statement if this return statement can never be reached due to an infinte loop... But add a break or return statement inside the loop (even inside an if statement which will never be executed) and the return statement after the "wannabe" finite loop will be required by the compiler This compile successfully (infinite loop, no return statement needed)But this doesn't compile (still infinite loop, but the compiler thinks it's not and gives an error for a missing return statement)And now the compiler is back happy, because after the "wannabe" finite loop there's a return statementAlso please note that a return statement is not really required, a throw statement will do the job too

    Hope it helps!
    Kind regards,
    Roel
     
    nick woodward
    Ranch Hand
    Posts: 370
    11
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    i guess i'm struggling slightly with the logic of allowing no return statement, rather than flagging the infinite loop itself as the problem.

    no doubt that's down to inexperience on my part, i'm sure there's a use for them.
     
    Ramya Subraamanian
    Ranch Hand
    Posts: 178
    17
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I've given a more detailed explanation in this post (included a possible scenario where this could be useful).


    Yeah, I was also talking about the same post.

    I think you are trying to give a scenario, of what will happen , incase the "if statements were to behave like while statements".



    or what issues would happen in realtime, if(DEBUG) was to throw a compiler error.

    But I misunderstood it as ... if(DEBUG) will actually throw a compiler error in your code
     
    nick woodward
    Ranch Hand
    Posts: 370
    11
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    just seen your edited post Roel - I was just running some (similar) code from the thread started by Mushfiq.



    as you can see by the name, i was skeptical, but i think i understand it now

    ifs allow unreachable looking code, and the break allows the possibility that 'after loop' can be reached, despite the compiler knowing it's an infinite loop.

    by the same logic, if a return type was defined here, it would have to be provided (or an explicit exception thrown)
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    nick woodward wrote:i guess i'm struggling slightly with the logic of allowing no return statement, rather than flagging the infinite loop itself as the problem.

    no doubt that's down to inexperience on my part, i'm sure there's a use for them.

    Let me provide a possible real coding example to give you the necessary experience to get a better understanding Agreed it's not using an infinite loop, but the concept is definitely the same. Fasten your seatbelt, here we go!

    Assume we have to process different kinds of values (e.g. list of all products, the product details based on an id, list of all product types, the product type description based on a code,...) from an input source (e.g. an XML file). When processing these values it's possible that for a kind of value some values are considered invalid (e.g. no products found in XML file) but for another kind of value every possible value is valid (e.g. not every product type has a description; if no description is found, the code is used). Let's focus on 2 of them: a list of all products and the product type description based on a code. There are many alternatives to implement this. Probably the most straightforward one is create a Processor interface and have two classes to implement this interface: GetListProductsProcessor and GetProductDescriptionProcessor (names should be pretty obvious). So a first design would look like thisOne of the drawbacks of this approach: besides the interface a developer can do whatever he likes. So one developer might opt to return null when the value is invalid, another one might want to throw a custom (runtime) InvalidValueException, someone else decides to (ab)use the IllegalStateException in this case, and so on. So a (possible) improvement would definitely be to add an AbstractProcessor class: this class defines the algorithm to be used and has protected abstract methods which must be implemented (and thus overridden) by the concrete classes to implement the required business logic. This AbstractProcessor class could look likeIf you look closely you'll notice that the process method is marked final. So subclasses can't override this method anymore and that's exactly what we want: every subclass must use the same algorithm to process the input source (and thus throw a runtime InvalidValueException when the value is considered to be invalid).
    Now we are ready for the next (and final) step: let the GetListProductsProcessor and GetProductDescriptionProcessor classes use (and benefit from) the AbstractProcessor class (so we only have to worry about implementing the business logic)So the exact same business logic is used as in the first implementation, but it's divided about several methods. And here you'll see several benefits of OOP and OOD: you are reusing code (algorithm of the AbstractProcessor class), less lines of code in each method (easier to read, maintain and test),...

    That was the (quite) big intro Back to the original topic and the unreachable code. Let's have a closer look at the getErrorMessage method of the GetProductDescriptionProcessor classBecause every processed value is valid for this class, this method should never be invoked. But this method expects a return value. We could provide an error message like "no description found for code[" + code + "]", but that's pretty useless as this method will never be executed. And because this method should never be executed, you want to know when it actually is invoked (hopefully during test and not in production ) because that indicates a bug somewhere in the algorithm and/or business logic. That's why this methods throws a runtime IllegalStateException and because the compiler knows this throw statement will always be executed, it doesn't complain about the missing return statement. In fact, if you would add a return statement, you'll get an "unreachable code" compiler errorSo in this case it's a awesome that the compiler doesn't flag the throw statement (like you suggested with the infinite loop), because this is exactly what we want! And you can (of course) not change the return type to void in this method because then this method would be an invalid override. And that's again something you don't want.

    I hope this post gives you some new insights why it would not have been a good idea if the compiler would flag the infinite loop itself as the problem! (Otherwise I have wasted several hours of my spare time ) This post doesn't only show a practical usage of a non-void method without return statement, but also provides a great (albeit small) lesson about OOP and OOD. And all for free!

    Hope it helps!
    Kind regards,
    Roel

    PS. This little story (and code) is a simplified version of a refactoring and redesign I have actually done in production code when I was working as a consultant at one of my customers! And that new design is running flawlessly for more than four years (and counting).
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ramya Subraamanian wrote:I think you are trying to give a scenario, of what will happen , incase the "if statements were to behave like while statements".

    That was indeed the intent of that post!

    If you would have a compile-time constant DEBUG set to true and use a bunch of if statements to print some additional info (during development and testing). But you would get compiler errors throughout your perfectly valid code in development and testing when you try to set it to false for the production release. Luckily the compiler allows conditional statements which will never be reached. The compiler gives a "dead code" compiler warning but not an "unreachable code" compiler error.
     
    Ganish Patil
    Ranch Hand
    Posts: 529
    19
    Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Unreachable code in exception handling.
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    nick woodward wrote:ifs allow unreachable looking code, and the break allows the possibility that 'after loop' can be reached, despite the compiler knowing it's an infinite loop.

    by the same logic, if a return type was defined here, it would have to be provided (or an explicit exception thrown)

    You are absolutely spot-on! Because the compiler doesn't care about unreachable if statements, the compiler thinks the loop will be finite at a given moment and therefore allows the statement after the (infinite) while loop.
     
    Ramya Subraamanian
    Ranch Hand
    Posts: 178
    17
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    One of the drawbacks of this approach: besides the interface a developer can do whatever he likes. So one developer might opt to return null when the value is invalid, another one might want to throw a custom (runtime) InvalidValueException, someone else decides to (ab)use the IllegalStateException in this case, and so on. So a (possible) improvement would definitely be to add an AbstractProcessor class

    We could use default or static methods of the interface in java 8. But then again, static or default methods cannot be made final. The developer can override it anyway... When you don't want this method to be tampered with .. Abstract class is always the best choice.

    That's why this methods throws a runtime IllegalStateException and because the compiler knows this throw statement will always be executed, it doesn't complain about the missing return statement.




    Good scenario and example of a non-void method without a return statement.

    I hope this post gives you some new insights why it would not have been a good idea if the compiler would flag the infinite loop itself as the problem!


    Yes, it would definitely benefit all of us .Amazed by your effort. Thanks for sharing your experience
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ramya Subraamanian wrote:We could use default or static methods of the interface in java 8. But then again, static or default methods cannot be made final.

    The default interface methods feature allows a developer to add new methods to an interface without breaking the existing implementations of this interface. It provides flexibility to allow an interface to define an implementation which will be used (as default) when a concrete class fails to provide an implementation for that method. So in this scenario it would not be the best design decision to use a default (or static) interface method to implement this behavior, because you are not extending the existing interface with a new method.

    Ramya Subraamanian wrote:Yes, it would definitely benefit all of us .Amazed by your effort. Thanks for sharing your experience

    Glad to hear this post was very helpful and you appreciate the effort
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic