检查两个对象是否不相等,除非它们都为空

Check if two objects are not equal, unless they are both null

下面的 Java 代码片段让我有点困惑。该方法试图检查两个对象是否 NOT 相等,使用标准 .equals() 方法表示它们相等。此外,布尔值可以确定两个空值是否被视为相等。我想知道是否:

片段:

public static void verifyVariableIsNotEqualTo(Object variable, Object otherVariable, boolean considerBothNullAsEqual)
{
    if(considerBothNullAsEqual && variable == null && otherVariable == null)
    {
        throw new Exception("not allowed to be equal");
    }

    if(variable == null || otherVariable == null)
    {
        return;
    }

    if(variable.equals(otherVariable))
    {
        throw new Exception("not allowed to be equal");
    }
}

是的,方法中的逻辑是正确的。如果两个对象相等,它会抛出异常。您可以删除第二个条件并将其与第三个条件结合起来,但我认为没有多大意义。如果你这样做了,方法可能看起来像这样。

public static void verifyVariableIsNotEqualTo(Object variable, Object otherVariable, boolean considerBothNullAsEqual) throws Exception
{
    if(considerBothNullAsEqual && variable == null && otherVariable == null)
    {
        throw new Exception("not allowed to be equal");
    }

    if(variable != null && variable.equals(otherVariable))
    {
        throw new Exception("not allowed to be equal");
    }
}

请注意,无需单独检查 otherVariable 是否为 null,因为 variable 上的 equals 方法应该 return false 如果 otherVariable 是空。

还有一种更简洁的写法,但不值得考虑,因为它牺牲了可读性。