Why does a method require a return value after an operator that always returns true?

Why does this method (test) require a return value (is it always true)?

public boolean test() { //This method must return a result of type boolean if (true) { return true; // always return true } } 

and when I added the return value, it warns as "Dead Code" . So why not accept the first test() method

 public boolean test(int i) { if (true) { return true; } else { //Dead code return false; } } 
+7
source share
5 answers

The method return analysis does not analyze the if condition to make sure that it is always true or false, because, as a rule, this will not be a compile-time constant (otherwise you will not write if in the first place). He simply sees that there exists an if that may or may not be accepted, and if it was not accepted, the method does not return a value, hence an error.

The dead code analysis is performed in a separate passage to the method return analysis, which does a more in-depth analysis that looks at the internal branching conditions.

My completely ignorant assumption is that this behavior is an artifact of how the compiler was designed; method return analysis is an important part of compilation so that you can get a valid program at the end, and this has become one of the main functions implemented in the first place. Parsing dead code is “nice to have,” and so it was implemented later using more sophisticated algorithms (since the bits of the main compiler were completed at this point)

+11
source

This is the result of the depth of analysis that the compiler does.

+2
source

This method does nothing, so yes, it is dead code. If the method always returns true, you do not need to call it, just use true instead.

+1
source

In Java, if you specify the type of the return value (boolean), you must explicitly specify the value, regardless of whether it is always the same. This raises the question: if it is always the same, why return anything? You already know the answer in the calling code.

Why not just write:

 public boolean test() { return true; } 

Regarding the second part of your question, the compiler sees that the second path is never accepted in the if statement and gives you a warning about this.

+1
source

If you are testing something, it could be a value or another value. Therefore, you cannot guarantee that this will happen inside the if statement.

 if (someBoolean){ return true; } 

will not work as someBoolean can be true or false. If your method should return something and someBoolean is false, it will not return anything. So in this case you can:

 if (someBoolean){ return true; } 

return false;

or simply

 return someBoolean; 
0
source

All Articles