IntelliJ IDEA: Boolean method XX is always inverted
try to return false
if bluetoothAdapter
is null otherwise return the output of isEnabled()
public static boolean isBlueToothEnabled(){
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter == null){
return false;
}
return bluetoothAdapter.isEnabled();
}
Read more:
In Clean Code, Robert Martin writes, “Negatives are just a bit harder to understand than positives. So, when possible, conditionals should be expressed as positives.” (Martin, [G29]). IntelliJ IDEA has three inspections to help you stay positive.
https://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/ (Entry #4 Avoiding negative Conditionals)
https://www.jetbrains.com/help/idea/2016.1/invert-boolean.html
Summary: Method always called like !method(). It's more efficient to have less number of computation. Refactor the method and return oppositely and call the method without (!)
Why it happens
If we have a method foo()
boolean foo()
{
if(condition == true)
return true;
else
return false;
}
And is only called like !foo()
,
class A
{
if(!foo())
do something;
...
if(!foo())
do something else;
}
Because we only call !foo()
and did not call foo()
.
The warning asks us to use foo()
in a positive way.
Remove the warning
By inverting the return value of the method foo(),
boolean foo()
{
if(condition == true)
return **false**;
else
return **true**;
}
Now call the method
class A
{
if(foo())
do the same thing;
}