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");
}
开发者_开发问答 }
It's not for readability, it's to prevent accidental assigning instead of comparing.
If you accidentally write:
if (conn = null)
in C or C++, that will set conn
to null
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 to triple-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:
if (conn = null) { ...
where the =
is assignment (when ==
comparison was intended). Modern compilers warn about this error, so this practice is not really needed any more.
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 do null=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.
String unknown;
String KNOWN = "Hello";
It is much better to do your comparison so:
if(KNOWN.equals(unknown)) do something;
As it saves a null check which if omitted could cause a runtime exception.
精彩评论