3

我有一个比较器在比较它们的内容之前检查两个对象的“null”。比较方法如下所示:

    public int compare(MyClass left, MyClass right) {
        if (left == null) {
            return right == null ? 0 : 1;
        }
        if (right == null) {
            return -1;
        }
        // do some other comparing
    }

当我通过声纳代码质量检查工具运行它时,它在 if 语句中报告“不兼容的位掩码”错误。(它的内容类似于:“正确性 - 不兼容的位掩码: (e | 0x1 = 0x0) 中的不兼容位掩码会在 ....Compare (MyClass, MyClass) 中产生恒定的结果。我看不出这是怎么回事。任何人都可以对此有所了解?这是误报吗?

顺便说一句,我使用的声纳版本是 2.6。

4

2 回答 2

6

我相信我知道发生了什么事。我相信您的代码是由 Clover 编织而成的,而 Clover 代码正在修饰该代码,并且它的执行方式并不那么干净。

44: sipush  14625
47: invokevirtual   #10; //Method com_cenqua_clover/CoverageRecorder.iget:(I)I
50: ifeq    57
53: iconst_1
54: goto    58
57: iconst_0
58: iconst_1
59: ior
60: ifne    85

这就是 FindBugs 所抱怨的。

于 2011-04-18T18:46:05.483 回答
-4
public int compare(MyClass left, MyClass right) {

    if (left == null) {
        return right == null ? 0 : 1;
    }
    if (right == null) {
        return -1;
    }
    // do some other comparing
}

此代码甚至不应该编译,因为在方法签名中您已同意此方法将返回 int 类型,但由于它只有 if 语句,因此在某些情况下它甚至可能不返回值。

现在来到您的“不兼容的位掩码”问题,这是因为对于 (right == null),该方法似乎返回两个值,即 0 和 1,尽管两者不同时。在您的工具声纳代码质量检查中,该方法似乎为相同的比较返回两个不同的值,因此一个值有时可能会隐藏另一个值。

于 2012-12-20T10:31:59.997 回答