Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ IDEA: Boolean method XX is always inverted

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; } 
like image 320
mobileDev Avatar asked Jun 27 '16 06:06

mobileDev


People also ask

How do you reverse a Boolean?

Press Ctrl+Shift+R and then choose Invert Boolean.

What is Boolean invert?

Invert Boolean The Invert Boolean refactoring lets you change the sense of a Boolean method or variable to the opposite one.


2 Answers

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

like image 95
Robin Vinzenz Avatar answered Sep 18 '22 11:09

Robin Vinzenz


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;     } 
like image 25
Amrit kumar Avatar answered Sep 18 '22 11:09

Amrit kumar