Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

NOTE: This article is 3 years or older so its information may no longer be relevant. Read on at your own discretion! Comments for this article have automatically been locked, refer to the FAQ for more details.
I've been doing some tricky debugging recently where I had to provide one of my web services that required the environment it ran in configured a very particular way. The developer I was working with did not have such an environment and there was no time to set one up properly. This was a bit of a dilemma, however the issue we were trying to debug didn't require my service to fully execute, it was sufficient to get to a particular point in the execution and exit, this could be done on a vanilla system.

The naive solution is to put in an early return statement in the code. However, the Java compiler detects this and you get a compiler unreachable statement error. There is a way around this though!

Lets look at some code to illustrate this.
 Test.java
public class Test {
public void doSomething() {
int i = 1;
int j = 2;
int k = i + j;
if (k != 3) {
throw new RuntimeException("Expecting 3!");
}
}
}


This code doesn't do anything useful, but for example purposes lets say we needed to return early from the method before the 'int k = i + j;' line was executed. We could try inserting a return statement like this...
 Test.java
...
int j = 2;
return;
int k = i + j;
...


Of course this would get a compile error...
Test.java:9: error: unreachable statement
int k = i + j;
^
1 error




So how do we trick the compiler in letting us return early? It's as simple as adding an invariant true condition to the return statement thus:
 Test.java
...
int j = 2;
if (1 == 1) {
return;
}
int k = i + j;
...


The condition inside the if statement will always evaluate to true (unless you're doing quantum computing maybe) so we will always execute the return statement and the compiler will not complain.

This is a trick and abuse of the language so it should not be used in normal programming situations, but under certain conditions this can make an invaluable debugging tool.

-i

Hope you found this post useful...

...so please read on! I love writing articles that provide beneficial information, tips and examples to my readers. All information on my blog is provided free of charge and I encourage you to share it as you wish. There is a small favour I ask in return however - engage in comments below, provide feedback, and if you see mistakes let me know.

If you want to show additional support and help me pay for web hosting and domain name registration, donations, no matter how small, are always welcome!

Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...