【发布时间】:2014-05-14 14:04:36
【问题描述】:
Eclipse 喜欢使用 nullcheck 生成 equals 方法(对于没有超类的类),如下所示:
if ( null == obj )
return false;
不过,我喜欢
if ( obj == null )
return false;
更多,因为它更具可读性。 (这一直困扰着我。)
问:
考虑到if ( null == obj ) 是此处所述源自 C/C++ 的过时做法,为什么 Eclipse 会在 obj 之前生成 null?:
(obj == null) vs (null == obj)?
两者之间有任何(运行时)差异吗?我只能推测...
更新:
Eclipse Kepler 似乎生成了if ( obj == null ),因此这仅适用于以前的 Eclipse 版本。
之前的课程:
public class Burp
{
private Long id ;
public Burp()
{
// test
}
}
课后:
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;
}
}
我认为我们需要清理 Kepler 之前生成的 equals 方法。
【问题讨论】:
-
if ( obj = null )在 Eclipse 和任何正确的 Java 编译器中产生错误。 -
您最终可能会得到答案“它必须是单向的,您认为更具可读性的内容不一定是每个人都认为更具可读性的内容”
标签: java eclipse code-generation equals