这种代码增强或实践称为什么? (null == conn) 与 (conn == null) 相反
我正在尝试编写一些代码增强的报告,但是,我不太确定该项目的名称。基本上,它不是执行 conn == null
,而是执行 null == conn
以提高可读性。
之前:
if (conn == null){
if (log.isDebugEnabled()){
log.debug("Failed to get a DB Connection");
}
}
之后:
if (null == conn){
if (log.isDebugEnabled()){
log.debug("Failed to get a DB Connection");
}
}
I am trying to make a report of some code enhancement, however, i am not too sure what this item is called. Basically, instead of doing a conn == null
, it does a null == conn
for readability.
Before:
if (conn == null){
if (log.isDebugEnabled()){
log.debug("Failed to get a DB Connection");
}
}
After:
if (null == conn){
if (log.isDebugEnabled()){
log.debug("Failed to get a DB Connection");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这不是为了可读性,而是为了防止意外分配而不是比较。
如果您不小心在 C 或 C++ 中编写:
,则会将
conn
设置为null
,然后使用该值作为条件。尽管 Java 中没有必要,但这一点已被延续到 Java 中。相反,编译器将其捕获为尝试分配给常量,因此它甚至无法编译。
至于它叫什么,我从来没有见过它有具体的名字。只要你解释一下,你就可以随心所欲地称呼它。我喜欢
避免意外赋值
,因为我可以将其缩短为triple-a
。It's not for readability, it's to prevent accidental assigning instead of comparing.
If you accidentally write:
in C or C++, that will set
conn
tonull
and then use that value as the condition. This has been carried over into Java despite the fact that it's not necessary there.The other way around, the compiler catches it as an attempt to assign to a constant so it won't even compile.
As for what its called, I've never seen it given a specific name. You can call it what you want provided you explain it. I like
Accidental assignment avoidance
since I can just shorten that totriple-a
.这种做法称为“在相等测试中将常量放在变量之前”。
表面上它的目的是避免特定类型的输入错误:
其中
=
是赋值(当==
比较 是有意的)。现代编译器会警告此错误,因此不再需要这种做法。This practice is called "putting the constant before the variable in an equality test".
Ostensibly its purpose is to avoid the a specific kind of typing error:
where the
=
is assignment (when==
comparison was intended). Modern compilers warn about this error, so this practice is not really needed any more.这只是为了避免错误地分配给变量。
也就是说,如果您使用
conn=null
,则 null 会被分配给该变量,但是,如果您使用null=conn
,那么编译器将出现错误,因为您无法分配给'无效的'。因此,它可以防止您错误地输入一个“=”而不是两个“==”的错误
It is just to avoid assigning to a variable by mistake.
That is if you use
conn=null
then null is assigned to the variable, however, if you donull=conn
then the compiler will through an error since you cannot assign to 'null'.So it prevents errors where you mistakenly type one '=' instead of two '=='
这种特定的语法毫无用处。但请考虑当您将具有未知初始化状态的对象与“常量”对象进行比较时。
最好这样进行比较:
因为它保存了空检查,如果省略该检查可能会导致运行时异常。
That particular syntax is quite useless. But consider when you are comparing an object with unknown initialization state to a 'constant' object.
It is much better to do your comparison so:
As it saves a null check which if omitted could cause a runtime exception.