I am getting warning " Boolean method is always inverted " on running lint in IntelliJ. I have several similar warnings in my codebase. Which basic coding style, am I missing?
public static boolean isBlueToothEnabled(){ final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if(bluetoothAdapter != null) return bluetoothAdapter.isEnabled(); return false; }
Press Ctrl+Shift+R and then choose Invert Boolean.
Invert Boolean The Invert Boolean refactoring lets you change the sense of a Boolean method or variable to the opposite one.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With