IntelliJ IDEA:布尔方法XX始终反转

mob*_*Dev 17 intellij-idea android-studio

在IntelliJ中运行lint时,我收到警告"布尔方法总是反转".我的代码库中有几个类似的警告.哪种基本的编码风格,我错过了吗?

public static boolean isBlueToothEnabled(){
    final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if(bluetoothAdapter != null)
        return bluetoothAdapter.isEnabled();
    return  false;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*enz 22

false如果bluetoothAdapter为null则尝试返回,否则返回输出isEnabled()

public static boolean isBlueToothEnabled(){
    final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if(bluetoothAdapter == null){
        return false;
    }
    return bluetoothAdapter.isEnabled();
}
Run Code Online (Sandbox Code Playgroud)

阅读更多:

在"清洁法典"中,罗伯特·马丁写道,"否定词比正面词更难理解.所以,在可能的情况下,条件应该表示为正数."(Martin,[G29]).IntelliJ IDEA有三次检查,以帮助您保持积极态度.

https://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/ (条目#4避免负面条件)

https://www.jetbrains.com/help/idea/2016.1/invert-boolean.html

  • 但是切换返回值的想法/目的是什么(我不会从你发布的链接中得到它). (3认同)
  • `@SuppressWarnings("BooleanMethodIsAlwaysInverted")` (2认同)

Amr*_*mar 10

节省时间:总是否定布尔方法调用.没什么好担心的.


为什么会这样

如果我们有方法 foo()

    boolean foo()
    {
        if(condition == true)
            return true;
        else
            return false;
    }
Run Code Online (Sandbox Code Playgroud)

并且只被称为!foo(),

    class A
    {
        if(!foo())
            do something;
        ...
        if(!foo())
            do something else;
    }
Run Code Online (Sandbox Code Playgroud)

因为我们只打电话!foo()而没打电话foo().

警告要求我们以foo()积极的方式使用.

删除警告

通过反转方法foo()的返回值,

    boolean foo()
    {
        if(condition == true)
            return **false**;
        else
            return **true**;
    }
Run Code Online (Sandbox Code Playgroud)

现在调用方法

    class A
    {
        if(foo())
            do the same thing;
    }
Run Code Online (Sandbox Code Playgroud)

  • 这很好,但这只是为了删除警告?有什么实际好处?或许像表演或其他什么? (2认同)
  • 用于否定结果的可忽略但不必要的开销。如果您的方法调用经常否定结果,那么您将具有相同的否定开销 (2认同)
  • @Hzzkygcs 是的。在这种情况下,编译器只是将“ifne”替换为“ifeq”指令,甚至在更复杂的表达式中,如“if (!foo() || bar())”。 (2认同)

Dae*_*pha 6

我必须说,在某些情况下,我认为这个警告甚至无法以合理的方式修复。以如下所示的代码为例:

boolean getInfo(Info info) {
    // Retrieve some info that can fail so the function returns true or false
}

void func() {
    Info info;

    if (!getInfo(info)) {
        // Failed; handle error, early out
        return;
    }

    // Do stuff

    if (!getInfo(info)) {
        // Failed; handle error, early out
        return;
    }

    // Do stuff

    if (!getInfo(info)) {
        // Failed; handle error, early out
        return;
    }

    // Do final calculations
}
Run Code Online (Sandbox Code Playgroud)

遇到这样的情况该怎么办?将函数重命名为notGetInfo()? getDesinformation()?失败时提前退出函数不会导致括号树不断增长吗?

  • 同意。为了可读性,这种模式要好得多......至少对于“boolean”返回来说。当我查看类的方法时,看到名为“getInfo”的方法比“failedToGetInfo”或“getInfoFailure”方法更有意义。这会让我对该方法的主要目的感到困惑;它是否执行某些操作,或者是否检查失败?另一方面,在这种情况下,可以说使用 void getInfo() 和失败时抛出异常(并在堆栈跟踪中找到解释)更优雅(并且仍然非常可读),而不是返回模糊布尔值。 (3认同)