user1884155
user1884155

Reputation: 3736

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:

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

Upvotes: 0

Views: 1498

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79828

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.

Upvotes: 1

Related Questions