简体   繁体   中英

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

The following Java snippet of code confuses me a bit. The method is trying to check whether two objects are NOT equal, using the standard .equals() method to denote that they are equal. Additionally, a boolean can determine whether two null's are considered equal or not. I'm wondering if:

  • The boolean logic in this method is indeed correct?
  • the return statement in the middle block can be omitted somehow. Could this logic be rewritten in a more concise or other way, maybe dropping the empty return, but keeping a high level of human readability of the code?

Snippet:

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");
    }
}

Yes, the logic in the method is correct. It throws the exception if the two objects are equal. You could remove the second condition and combine it with the third one, but I don't see much point. If you did, the method might look like this.

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");
    }
}

Note that there's no need to check whether otherVariable is null separately, since the equals method on variable should return false if otherVariable is null.

There's an even more concise way to write this, but it's not worth considering, since it sacrifices readability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM