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

时间:2016-06-27 06:40:40

标签: android-studio intellij-idea

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

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

4 个答案:

答案 0 :(得分:19)

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

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

了解更多:

  

在“清洁法典”中,罗伯特·马丁写道,“否定者只是有点困难   理解而不是积极的。因此,在可能的情况下,条件应该   表达为积极的。“(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

答案 1 :(得分:8)

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

为什么会发生

如果我们有方法foo()

    boolean foo()
    {
        if(condition == true)
            return true;
        else
            return false;
    }

仅被称为!foo()

    class A
    {
        if(!foo())
            do something;
        ...
        if(!foo())
            do something else;
    }

因为我们只拨打!foo()并且没有拨打foo()

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

删除警告

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

    boolean foo()
    {
        if(condition == true)
            return **false**;
        else
            return **true**;
    }

现在调用方法

    class A
    {
        if(foo())
            do the same thing;
    }

答案 2 :(得分:0)

为简化起见,请参见以下代码:

public boolean isBoy(int sex){ return sex == boy};

if(!isBoy(sex)){ // todo}

If do so, it called inverted. How to solve? see the other code below:

public boolean isGirl(int sex){ return sex == girl};

if(isGirl(sex)){ // todo}

因为您需要判断条件是否是女孩,所以应避免判断是否是男孩,并加一个“!”。

答案 3 :(得分:0)

我必须说,在某些情况下,我认为此警告甚至无法以合理的方式解决。以如下代码为例:

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
}

在这种情况下该怎么办?将函数重命名为notGetInfo()吗? getDesinformation()?难道不是因为出现故障而过早退出功能,导致括号树不断增长?

相关问题