If (null! = Variable), why not if (variable! = Null)

Hello In our company, they adhere to a strict rule of comparison with zero values. When I encode if (variable! = Null) in a code review. I get comments on this to change it to if (null! = Variable) . Is there any performance hit for the above code? If someone explains that he is much appreciated.

Thank you in advance

+4
source share
4 answers

I see no advantage in complying with this agreement. In C, where Boolean types do not exist, it is useful to write

if (5 == variable) 

but not

 if (variable == 5) 

because if you forget one of the eaqual badges you will get

 if (variable = 5) 

which assigns the variable 5 and always evaluates to true. But in Java, the boolean is boolean. And with! =, There is no reason.

One good piece of advice, however, is to write

 if (CONSTANT.equals(myString)) 

but not

 if (myString.equals(CONSTANT)) 

because it helps to avoid NullPointerExceptions.

My advice would be to ask for an excuse for the rule. If they are not, why should they follow? This does not help readability.

+10
source

The lack of performance difference is the reason that if you are used to writing (null == somevar) instead of (somevar == null) , then you will never accidentally use one equal sign instead of two, because the compiler will not allow this, where it will allow (somevar = null) . They simply extend this to != To keep it consistent.

I personally prefer (somevar == null) myself, but I see where they came from.

+3
source

This is the "left" of the old C-coding standards.

the if (var = null) will compile without any problems. But it actually sets the null value of the variable, doing something completely different. This was the source of very annoying bugs in C programs.

In Java, this expression does not compile, and therefore, it is more a tradition than anything else. This does no purpose (other than coding style preferences)

+3
source

This has nothing to do with performance. This was used to prevent accidental assignment instead of comparison. Assigning null = var does not make sense. But in Java, var = null also not compile, so the rule of turning them no longer makes sense and makes the code less readable.

+2
source

Source: https://habr.com/ru/post/1339564/


All Articles