Reputation: 14003
Eclipse likes to generate equals
methods (for classes having no super class) with a null
check 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.
Upvotes: 4
Views: 556
Reputation: 4252
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.
Upvotes: 3
Reputation: 2158
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.
Upvotes: 4
Reputation: 41
also some people like Master Yoda style where you compare constant and then varible
if (5 == i) -- Yoda style
Upvotes: 1
Reputation: 328735
There is no difference and the convention in Java (if we assume that the JDK is a reference) is to use if (obj == null)
. See for example the code of Objects#requireNonNull
:
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
For what it's worth, Netbeans auto-generates equals
with if (obj == null) return false;
.
Whichever you use won't make a difference at runtime and will generate the same bytecode.
Upvotes: 2