Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse generating equals method: if ( obj == null ) vs. if ( null == obj )

Eclipse likes to generate equals methods (for classes having no super class) with a nullcheck like this:

if ( null == obj )
    return false;

However, I like

if ( obj == null )
    return false;

much more, because it is more readable. (It kind of disturbs me all the time.)

Q:

Why does Eclipse generate it with null coming before obj, given that the if ( null == obj ) is an obsolete practice stemming from C/C++ as described here?:

(obj == null) vs (null == obj)?

Are there any (runtime) differences between the two? I can only speculate...


Update:

Eclipse Kepler seems to generate if ( obj == null ), so this applies to former Eclipse versions only.

Class before:

public class Burp
{
    private Long id ;

    public Burp()
    {
        // test
    }
}

Class after:

public class Burp
{
    private Long id ;

    public Burp()
    {
        // test
    }

    // hashCode() omitted

    @Override
    public boolean equals( Object obj )
    {
        if ( this == obj )
            return true;
        if ( obj == null )
            return false;
        if ( getClass() != obj.getClass() )
            return false;
        Burp other = ( Burp ) obj;
        if ( this.id == null )
        {
            if ( other.id != null )
                return false;
        }
        else if ( !this.id.equals( other.id ) )
            return false;
        return true;
    }
}

I think we have some cleaning up to do for our pre-Kepler generated equals methods.

like image 238
Kawu Avatar asked Dec 26 '22 09:12

Kawu


2 Answers

Some people write null == obj instead obj == null, because there is no risk to type = instead of ==, but it doesn't change how your code works. Keep in mind that in Java it's only possible to write obj = null (without an error) when obj is Boolean. This way of writing code comes from other programming languages like C where it's completely valid to write obj = null by mistake.

like image 99
Jakub H Avatar answered Jan 13 '23 11:01

Jakub H


You can modify the template for generating equals method in Eclipse, refer the following link

As far as Runtime differences between the two are concerned I think both the expressions should be the same as the compiler would optimize both the null check expressions in a similar way (i.e same bytecode will be generated). Its more about what conventions people like to use , and it varies from person to person.

like image 23
Kakarot Avatar answered Jan 13 '23 12:01

Kakarot