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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With