Android Studio reports "Unreachable Code" with enum comparison - java

I'm doing something that should be trivial- retrieving an enum value from a property and comparing it with a constant of that enum in an if statement. However Android Studio claims the true case is unreachable code and won't compile.
The block is:
if (ScanState.getScanMode() != ScanState.ScanModeEnum.SCAN_IDLE)
{
//We're already scanning, but user wants to stop.
stopScanning();
}
else
{
ScanState.setScanMode(newMode);
restartScan();
buttonFlashMode = btnMode;
buttonFlasher();
}
where in an extra ScanState class, I have:
public static ScanModeEnum getScanMode() {
return scanMode;
}
public static void setScanMode(ScanModeEnum scanMode) {
ScanState.scanMode = scanMode;
}
public enum ScanModeEnum
{
SCAN_IDLE,
SCAN_PERSON,
SCAN_BIKE,
SCAN_SEARCH
}
private static ScanModeEnum scanMode = ScanModeEnum.SCAN_IDLE;
Variants I've tried, which Android Studio claims will all evaluate to false are
if(ScanState.getScanMode() == ScanState.ScanModeEnum.SCAN_IDLE)
if(ScanState.getScanMode().compareTo(ScanState.ScanModeEnum.SCAN_IDLE)!=0)
if(ScanState.ScanModeEnum.SCAN_IDLE == ScanState.ScanModeEnum.SCAN_IDLE)
if(ScanState.ScanModeEnum.SCAN_IDLE.equals(ScanState.ScanModeEnum.SCAN_IDLE))
I'm new to Java (more familiar with C#), but an answer to this question suggests that my understanding of this is sound. Is there some stupid mistake I'm making?

Have you tried debugging this and verifying that the block is never actually reached?
I agree this is a very strange situation. If it persists, I can recommend swapping the enum for int constants, and conducting the check on them. It's not a real fix, but more of a workaround, but at least it can unblock you for the moment.

Good grief. After making a seperate method as suggested and discovering the problem lay elsewhere I had a look further up the code. The complete method was;
public void onScanButtonPress(#ButtonFlashMode int button)
{
ScanState.ScanModeEnum newMode;
#ButtonFlashMode int btnMode = 0;
switch (button)
{
case FLASH_BIKE:
newMode = ScanState.ScanModeEnum.SCAN_BIKE;
btnMode = FLASH_BIKE;
case FLASH_PERSON:
newMode = ScanState.ScanModeEnum.SCAN_PERSON;
btnMode = FLASH_PERSON;
default:
//Unhandled.
return;
}
if (ScanState.getScanMode() != ScanState.ScanModeEnum.SCAN_IDLE)
{
//We're already scanning, but user wants to stop.
stopScanning();
}
else
{
ScanState.setScanMode(newMode);
restartScan();
buttonFlashMode = btnMode;
buttonFlasher();
}
}
Since I've forgotten to put break statements in the cases of the switch, it'll always return before the if is ever evaluated. It'll therefore never evaluate to true and so the error is correct- if misleading since it implies (to me at least!) that the if statement does get evaluated. Thanks for the comments, and I figured this was worth leaving (despite being indeed a stupid mistake) because others might be caught out by this.

EDIT: As mentioned by #Bubletan and #MarkoTopolnik, this would not result in a compiler error. Leaving the response as documentation of something that would NOT cause this error.
Do you call anywhere in your code setScanMode? (outside that else block). The compiler may be detecting that the static variable scanMode is never modified, and therefore ScanState.getScanMode() is always ScanState.ScanModeEnum.SCAN_IDLE, thus code not reachable.
Try invoking setScanMode somewhere in your code (with a value different than ScanState.ScanModeEnum.SCAN_IDLE) and see if this error disappears.

Related

Java Error/Exception handling with returning value

So my friend and I are programming Blackjack in Java, and we wanted to test our input fields for the correct input(e.g only number input). So we sat at his PC and he wrote this solution:
public static boolean testeTextFieldInt(JTextField textField, int geld) {
if (!textField.getText().isEmpty()) {
try {
if(Integer.parseInt(textField.getText())>0 && Integer.parseInt(textField.getText())<geld ) {
return true;
}
} catch (NumberFormatException e) {
return false;
}
}
return false;
}
now I disagree with this solution, because your code shouldn't depend on an error, or am I getting this wrong? so i sat down and wrote this:
public static boolean checkInput(JTextField textField, int spielerGeld, String eingabe) {
boolean matched = false;
switch (eingabe) {
case "num":
if (!textField.getText().isEmpty() && textField.getText().matches("^[0-9]*$")) {
int geldinput = Integer.parseInt(textField.getText());
if (geldinput > 0 && geldinput < spielerGeld) {
matched = true;
}
}
break;
case "string":
if (!textField.getText().isEmpty() && textField.getText().matches("^[a-zA-Z]*$")) {
matched = true;
}
break;
default:
break;
}
return matched;
}
Keep in mind, we yet dont have any textfields we have to check, but I just implemented it to get a grasp of how you could do multiple checks within one method.
So now my question is, what code is "better"? and what could we/I do better?
Thanks in advance!
EDIT1:
So as some already have mentioned, you say my method is not build up after the Single responsibility principle.
But if split up into 'checkInputIsnumber' and checkInputIsString' would the first solution(my friend), still be the "better" one?
EDIT2:
Better is defined as in, the method should be of low cyclomatic complexity, easy readability and be easy to maintain in the long run.
The first approach is much better than the second one.
Single responsibility: You should avoid creating methods that do more than one thing.
Open–closed principle: Your 'validation' is not extensible. Try creating a Validator interface and then an implementation per validation type.
Switch statements increase cyclomatic complexity and make testing harder.
Also, don't use textField.getText() everywhere, it's quite possible that it will change between calls. Assign it to a local variable or even better use a String as your argument and not JText. As Fildor pointed out you correctly avoid using exceptions for flow control and it is indeed better to have a single return point. Having said that, for simple cases when you just parse/check and return, it is acceptable.
You should put every check in a single function. After a while your "all in one function" will be unreadable an unmaintainable. Also it easier to change the checks if they are in single functions. Using try/catch for control flow is no good idea. It is expensive at runtime. It is not a good style and most developers won't expect control flow in a catch block.Excpetions are for exceptional situations.

Why does compiler build return unreachable code in some cases

If I write
private void check(){
if(true)
return;
String a = "test";
}
Above code works normally, but if I write
private void check(){
return;
String a = "test";
}
The compiler/gradle in Android studio doesn't let this one through even though it's the same, and it says that the code after return in example 2 is unreachable.
I don't have any issues regarding this but I am eager to know why?
javac compiler does very little optimizations, so it simply does not "see" that if(true) is always true(but you should get a warning); but C1/C2 JIT compilers will - so that code will simply be a return, without an if statement.
This is explained by the Unreachable Statements part of the Java Language Specification.
There are quite a few rules, with an interesting special case. This is a compile time error :
while (false) {
// this code is unreachable
String something = "";
}
while this is not :
if (false) {
// this code is considered as reachable
String something = "";
}
The given reason is to allow some kind of conditional compilation, like :
static final boolean DEBUG = false;
...
if (DEBUG) { x=3; }
So in your case :
private void check(){
if(true)
return;
// NO compilation error
// this is conditional code
// and may be omitted by the compiler
String a = "test";
}
is not an error because of the special if treatment, using while instead is not accepted :
private void check(){
while(true)
return;
// "Unreachable statement" compilation error
String a = "test";
}
This is also en error :
private void check(){
if(true)
return;
else
return;
// "Unreachable statement" compilation error
String a = "test";
}
When it tries to compile it builds an abstract syntax tree. In the first case 'true' is an anonymous variable, so two branches will be added, even only one of them is possible. In the 2nd case, there is only one possible branch to create, which will never reach its end.
The difference is these require two different analyses to determine the behavior. The first example requires semantic analysis while the later requires syntactical analysis. Compilers are experts in syntax; this is what they are built to do. They often struggle with semantics, though. Performing static semantic analysis takes more effort from the compiler writers and can be extremely difficult to get correct in general.

What causes a method to be classed as "'not compilable (disabled)" by the hotspot compiler?

After making some changes to an application it suffered a significant performance degradation and on investigation one of the most frequently called methods is no longer being compiled. Turning on: -XX:+LogCompilation shows that before the change, this method was: queued for compilation, compiled, and then successfully inlined into callers; whereas after the change, there is no record of a compilation attempt and the inlining attempt says:
inline_fail reason='not compilable (disabled)'
The original method is as follows, where _maxRepeats is an instance variable declared as a Map (no generics, code written a long time ago), used such that the key was an object of class DadNode and the value was an Integer.
private int cnsGetMaxRepeats(DadNode dn) {
if (_maxRepeats != null) {
Integer max = (Integer)_maxRepeats.get(dn);
if (max != null) {
return max;
}
}
return dn.getMaxOccurs().getValue();
}
The amendment involved changing the _maxRepeats map to use generics:
Map<Integer, Integer>
and a new parameter was added to the method:
private int cnsGetMaxRepeats(int childIdx, DadNode dn) {
if (_maxRepeats != null) {
Integer max = _maxRepeats.get(childIdx);
if (max != null) {
return max;
}
}
return dn.getMaxOccurs().getValue();
}
Using explicit calls to Integer.valueOf and Integer.intValue to avoid autoboxing make no difference; the method is still not compilable.
I can "poke it with a stick" until I get a solution which does what I want (and is also compilable), but what are the criteria behind this disabling?
I think a basic mistake on my part - the log with the "compilation disabled" method was produced when running debug through IntelliJ (although with breakpoints muted). I expect IntelliJ disables compilations for methods with breakpoints in, even when muted.
So to answer my own question, I have no reason to think that anything apart from explicitly disabling compilation will do so.

How to refactor to avoid passing "special values" into a Java method?

I'm sure there must be a standard way to do this, but my attempts to search Stackoverflow have failed.
I have a method like:
public void processSomeWidgetsForUser(int userItemId) {
Iterator<Widgets> iter = allWidgets.values().iterator();
while(iter.hasNext()) {
Widget thisWidget = iter.next();
if (userItemId == -1 || thisWidget.getUsersItemId() == userItemId) {
widget.process();
}
}
}
As you can see -1 is a "special value" meaning process all. Doing this saves repeating the loop code in another method called processSomeWidgetsForAllUsers.
But I dislike special values like this because they are easy to misuse or misunderstand, which is exactly the situation what I'm having to fix now (where someone thought -1 meant something else).
I can only think of two ways to improve this.
have a constant, containing -1 called something like
Widget.ALLWIDGETS which at least is self-documenting, but doesn't
stop code from using a -1 (if someone integrates old code in, for
example)
change the method to take a list of all user ids to
process, which can be empty, but that doesn't seem great
performance-wise (would need to retrieve all user ids first and then loop through
removing. Also what happens if the number of widgets in the list changes between
retreiving the ids and removing
Is there a better way? I'm sure I'm missing something obvious.
The above code has been changed slightly, so may not compile, but you should get the gist.
Although somewhat redundant, a fairly neat self-documenting approach could be to have 3 methods rather than one;
Make your original method private, and make one small change which would be to add your static final int EXECUTE_ALL = -1 and use that in your original method, then add the two new methods;
public void processWidget(int wID) throws IllegalArgumentException {
if(wID == EXECUTE_ALL) throw new IllegalArgumentException();
originalMethod(wID);
}
public void processAllWidgets() {
originalMethod(EXECUTE_ALL);
}
It makes your class a little more cluttered, but as far as the exposed methods go, it is clearer and hopefully foolproof. You could alter it not to throw an exception and just ignore any invalid ids, that just depends on your situation.
This approach of course has the major downside that it changes how the class appears to other classes, breaking everything that currently uses the, now private, originalMethod().
Number 1 would work very nicely. Be sure to document what the variable is though, so future coders (possibly yourself) know what it means.
/**This is the explanation for the below variable*/
public final static int ALL_WIDGETS = -1;
Have an external method like so:
static boolean idRepresentsAll(int id) {
return id == -1;
}
In this case, if you decide to replace it with a different mechanism, you only replace your magic number one place in your code.
At the very least, you would want to do something like this:
public static final int ID_REPRESENTING_ALL = -1;
You can change the method signature to accept a boolean for when you want to process them all.
public void processSomeWidgets(boolean doAll, int userItemId) {
Iterator<Widgets> iter = allWidgets.values().iterator();
while(iter.hasNext()) {
Widget thisWidget = iter.next();
if (doAll || thisWidget.getUsersItemId() == userItemId) {
widget.process();
}
}
}
This makes it more explicit, and easier to read in my opinion as there are no special values.

what does Dead Code mean under Eclipse IDE Problems Section

I am using Eclipse Helios IDE for our Web Application development.
Under Problems section in Eclipse, for some of lines the description is displayed as "Dead Code".
Could anybody please tell me what does Dead Code actually mean ?
Please see the screen shot for your reference.
For example this part is shown as dead code under Eclipse
else {
int length;
if (ar != null)
length = Array.getLength(ar);
else
length = 0; // This line is dead code
In Eclipse, "dead code" is code that will never be executed. Usually it's in a conditional branch that logically will never be entered.
A trivial example would be the following:
boolean x = true;
if (x) {
// do something
} else {
// this is dead code!
}
It's not an error, because it's still valid java, but it's a useful warning, especially if the logical conditions are complex, and where it may not be intuitively obvious that the code will never be executed.
In your specific example, Eclipse has calculated that ar will always be non-null, and so the else length = 0 branch will never be executed.
And yes, it's possible that Eclipse is wrong, but it's much more likely that it's not.
Dead code is code that will never be executed, e.g.
boolean b = true
if (!b) {
....
// dead code here
}
Dead code means, that there is no way that this code will be executed.
Sometimes you even can't compile it (like this case:)
private Boolean dead_code()
{
return true;
//Dead code below:
dosomething();
}
But in other cases this is not too obvious, eg this statement:
b=true;
[...]
if (b==false)
{
//Dead code
}
If you have this message, there is some major flaw in your code. You have to find it, otherwise your app won't work as intended.
There are two kinds of diagnostics that Eclipse gives out for marking code that will/may not be executed at runtime.
1) Unreachable code: These are the usual java warnings that follow the unreachability rules of the JLS, and are also given by javac. These are meant to be compile errors. Examples:
int foo() {
return 1;
int i = 1; // Unreachable
}
int foo2() {
while (true);
int i =1; //Unreachable
}
There are other more complicated examples :)
2) Dead code: This is Eclipse's own static analysis warnings, and are mostly tied out of the null analysis i.e.
void foo() {
Object o = null;
if (o == null) {
} else {
// dead code
}
The examples given above should NOT give a dead code warning. i.e.
boolean x = true;
if (x) {
// do something
} else {
// this is dead code!
}
should not give the warning, because JLS forbids the compiler to evaluate the 'value' of variables. All that we can evaluate is the 'nullness'
Hope this helps
You might be having an Null pointer exception in the lines above the "Dead Code" lines.
Make sure you check for "Null Pointer" exception.
It is possible that you have used the variable ar before. Then the compiler knows that the line in the else statement will never be executed. Either there will be a NullPointerException at the place where you used ar or the first part of the if statement will be executed.
let me give some answer for the dead code.
Eg:
public class UnreachableTest{
public static void main(){
try{
// some code
}
catch(Exception exc){
throw new NullPointerException();
System.out.println("Unreachable line"); // compile time error
}
}
}
here the System.out.println("Unreachable line"); is never executed.
Which in turn considered to be a dead code.
Another example may be:
int func(int i, int j)
{
int sum = i + j;
return i + j; // never actually using the sum
}
simple the function returns i + j; never really uses sum.
Sum is considered to be dead code here.
Some other case when this happens.
System.out.println("result :" + result + ":" + result.isEmpty());
if (result == null)
return result;
else if(!result.isEmpty())
str.append(result + " ");
1) Here as you you are printing result and checking isEmpty() eclipse assumes that result is not null so it will not go in if. So return result is dead code.
2)Now let say result is coming null so you will get NullPointerException in result.isEmpty() so again it will not go in if and return result is deadcode
To make this work just comment out System.out.println().
Eclipse gives this warning if the condition check you are giving may never be satisfied. Following are some examples
Object o=null;
if(o!=null) {
//Some code
}
Here Dead code warning will come as Object is already made null
Another example is given below
BSTTest bstTest=null;
bstTest.test=10;
if(bstTest==null) {
//some code
}
Here the code is trying to access a variable of the class. As the variable is already accessed, eclipse will give dead code warning in if(bstTest==null) as bstTest may not be null when the variable is already accessed.
Note: Here bstTest.test will give null pointer exception
Simple Example of Dead Code
public class IfTest {
public static void main(String[] args) {
if (true) {
if(false) {
System.out.println("a"); //Dead code, Never be Execute this if block.
}else {
System.out.println("b");
}
}
}
To simplify the term's Unreachable code and dead code:
Unreachable Code is a code block/statement in Java to which the control never reaches and never gets executed during the lifetime of the program. Following is the example of unreachable code. This generates compiler time error.
public void unreachableCodeExample() {
System.out.println("This will execute");
return;
System.out.println("This will not"); //This is Unreachable code
}
While A Dead code is an unreachable code, but it doesn’t generate compile time error. But if you execute it in eclipse (Or some other IDE) it gives you a warning. See below example,
public void deadCodeExample() {
if (true) {
System.out.println("This will execute");
return;
}
System.out.println("This will not"); //This is dead code
}
Dead code is the section of our code that is never going to execute runtime, its useless
EX:
if(false){ // statements }
For more example u can refer : DeadCode Examples
Try this:
while (true) {
if(false == true) break;
}
S.O.P("I will never reach here!") <-- This code will never be executed.
The code is valid as it conform to the compiler, however in reality the loop will never exit, and in effect S.O.P will never be executed.

Categories

Resources