In fact NetBeans was as smart as it could be. It should look like this:
return num >= 0;
Now, what is the result of the expression num >= 0
? He's a Boolian, right? That is, the result of this "account" will be false
, or true
. It is either "greater than or equal to zero," or it is not. This can only happen.
So why not use this direct result? If you need to set a true
when this expression results in true
and you need false
when the expression results in false
, then use the result of the expression and simplify the logic.
One thing I realize is that it has a lot of programmers thinking that if
is a magic thing, and that you have a condition in there. In fact if
expects a Boolean expression, a conditional expression. It can be a literal , a simple variable , or a complex expression whose result is Boolean.
All this is valid (even if the first one does not make sense except for testing):
//literal
if (true)
//variável
variavel = outraVariavel > 0 && maisUmaVariavel.equals("teste");
if (variavel)
//expressão
if (outraVariavel > 0 && maisUmaVariavel.equals("teste"))
The if
is for flow control, it only decides if it should execute one block or another, if available. The decision is given by any Boolean value, whence it comes, it does not matter. The code of this method does not need a flow control, it just needs a Boolean result.
The same goes for while
and for
. It is only flow control whose decision is to deviate to another line or continue in the next is determined by a Boolean value that can be obtained by one of the three forms mentioned above.
Do as you will be simplifying the code and getting the same result:
public boolean isPositive(float num) {
return num >= 0;
}
Further reading .