Friday, January 15, 2010

A coding convention of JAVA

I read a post about how to wirte JAVA in java-style. Here is a interesting item:

Use s == null, not null == s

It's true that I use null == s when I write c programming and it is really useful. The author explained why JAVA does not use null == s. In JAVA world, it will cause compile error when using statements below:
if( iNum = do_some_check()) {do_some_thing(iNum);} /*............Statement 1*/

We should use in JAVA world:
iNum = do_some_check();
if(iNum!=0){do_some_thing(iNum);} /*............Statement 2*/

C programmers often use Statement 1 to save semantics, because it is totally legal to use "assign operater in "if" statement in C's world. If C programmer is "too tired", she/he will write incorrect semantic statement below to check iNum is equal to 99:
if(iNum = 99){do_some_thing(iNum)};/*............Statement 3*/

Hence, there is a common sense to check iNum is equal to 99 like this:
if( 99 == iNum){do_some_thing(iNum)};/*............Statement 4*/

However, we are free to this kind of fear in JAVA's world. We do not have to write JAVA like other languages.
FYI:
Speaking the Java language without an accent: http://www.ibm.com/developerworks/java/library/j-noaccent.html?ca=drs-