if(null!=variable) why not if(variable!=null) - java

Hi
In our company they follow a strict rule of comparing with null values. When I code
if(variable!=null) in code review I get comments on this to change it to if(null!=variable). Is there any performance hit for the above code?
If anybody explains highly appreciated.
Thanks in advance

I don't see any advantage in following this convention. In C, where boolean types don't exist, it's useful to write
if (5 == variable)
rather than
if (variable == 5)
because if you forget one of the eaqual sign, you end up with
if (variable = 5)
which assigns 5 to variable and always evaluate to true. But in Java, a boolean is a boolean. And with !=, there is no reason at all.
One good advice, though, is to write
if (CONSTANT.equals(myString))
rather than
if (myString.equals(CONSTANT))
because it helps avoiding NullPointerExceptions.
My advice would be to ask for a justification of the rule. If there's none, why follow it? It doesn't help readability.

No performance difference - the reason is that if you get used to writing (null == somevar) instead of (somevar == null), then you'll never accidentally use a single equals sign instead of two, because the compiler won't allow it, where it will allow (somevar = null). They're just extending this to != to keep it consistent.
I personally prefer (somevar == null) myself, but I see where they're coming from.

It's a "left-over" from old C-coding standards.
the expression if (var = null) would compile without problems. But it would actually assign the value null to the variable thus doing something completely different. This was the source for very annoying bugs in C programs.
In Java that expression does not compile and thus it's more a tradition than anything else. It doesn't erver any purpose (other than coding style preferences)

This has nothing to do with performance. It's used to prevent that you assign accidentally instead of comparing. An assignment null = var won't make any sense. But in Java var = null also won't compile so the rule of turning them around doesn't make sense anymore and only makes the code less readable.

Related

Compare constant equals object or object equal constant

Follow Java best-java-coding-practices.htm, they say we need call .equals on known string constants rather than UNKNOWN variable
String string = new Test().getString();
// always compare like this, this will never throw NPE
System.out.println("CONSTANT.equals(string):"+CONSTANT.equals(string));
System.out.println("Comparision like string.equals(CONSTANT) may throw NullPointerException");
// next statement will throw NPE
System.out.println("string.equals(CONSTANT):"+string.equals(CONSTANT));
So how about KNOWN variable? Should we still use this way or not?
For example, if I receive an object from server and server notify that this object never null.
In case I want to compare this object with a constant
// CONS: it may return NPE if server return null (for example server do wrong) => app crash
// PRO: when we read this code, we have a mindset that object never null, if it null it is the server bug
object.equals(CONSTANT)
// CONS: When we read this code, we never know why and when object == null so it confusing.
// It not return NPE so code still running and we may have some problem with UI or logic
// PRO: it never return NPE
CONSTANT.equals(object)
Any suggestions would be much appreciated. For me, I prefer object.equals(CONSTANT) for known variable but my team not.
UPDATE I think
CONSTANT.equals(object)
similar too
try{
object.equals(CONSTANT)
catch(NullPointerException ex){
// don't handle or explain anything
}
The practice of reversing the terms around the equality operator when one of the terms is a constant is called a Yoda conditional. You might encounter it in the following forms:
if( constant == variable ) instead of if ( variable == constant )
if( constant.equals( variable ) ) instead of if( variable.equals( constant ) )
Do not use Yoda conditionals. The Principle of Least Surprise is not just violated by this construct, it is gang-raped.
Also, this is a form of "defensive programming". Do not engage in defensive programming; engage in offensive programming instead. Read Trevor Jim's post Postel's law is not for you.
Also, do not blindly follow some advice just because someone calls it a "best practice". Who says it is a best practice?
Is it just a couple of folks out there? then by definition, they are not entitled to dress their subjective opinion with an objective title like "best practice".
Is it the majority of the industry? The majority is usually wrong. (Some might even say always wrong, watch Paul Rulkens # TEDxMaastricht 2014)
Is it virtually everyone in the industry? Then clearly, the industry is engaging in groupthink.
Here are the reasons often cited for using Yoda conditionals, and their rebuttals:
Alleged reason #1
Statement: It will catch accidental use of the assignment operator where the equality operator was intended.
Rebuttal: Such accidental use should be impossible because your compiler or your IDE should be issuing a warning if you try to do this. If you are not receiving a warning, then you have other, much bigger problems in need of solving, i.e. using the wrong programming language, using the wrong IDE, or trying to write code without first having figured out how to enable all warnings.
Alleged reason #2
Statement: It works even if the variable accidentally happens to be null.
Rebuttal: No, it does not work; it silently fails. If you follow offensive programming, the definition of "it works" is that it must produce correct results when given valid input, and it must deliberately fail when given invalid input. So, there are two possibilities: either the variable may legitimately be null, or it may not.
if the variable may legitimately be null, then explicitly check against null.
if the variable may not be null, then write the code so that it will not fail to fail in the event that the variable is in fact null.

Checking a variable on null value styles

I have 2 java statements:
if(myvar!=null)
if(null!=myvar)
Some people says that second form is better because it helps to avoid NPEs, is it true? What is generally beter to use in java?
if(myvar!=null)
if(null!=myvar)
Some people says that second form is better because it helps to avoid
NPEs, is it true?
No. These are exactly the same, and there is no risk of NPE here to avoid.
Maybe you confused the example with this situation:
if (myvar.equals("something"))
if ("something".equals(myvar))
Here, if myvar is null, the first form would throw an NPE, since .equals would be dereferencing a null value, but the second one works just fine, as the .equals implementation of String handles a null parameter gracefully, returning false in this example. For this reason, in this example, the 2nd form is generally recommended.
A related argument, which one of these is preferred?
if (myvar == null)
if (null == myvar)
Consider the possibility of a typo, writing a single = instead of ==:
if (myvar = null)
if (null = myvar)
If myvar is a Boolean, then the first form will compile, the second form will not. So it may seem that the second form is safer. However, for any other variable type, neither form will compile. And even in the case of a Boolean, the damage is very limited, because regardless of the value of myvar, the program will always crash with an NPE when the if statement is reached, due to unboxing a null value.
Since no test will ever get past this statement, and since you should not release untested code, making such mistake is unrealistic.
In short, the safety benefit is so marginally small that it's practically non-existent, so I don't see a reason to prefer this unusual writing style.
Update
As #Nitek pointed out in a comment, an advantage of adopting the second form could be if you make it a habit, so that when you program in other languages where myvar = null might compile, you'd be slightly safer, out of your "good habits".
I'd still point out that in many languages comparisons with null are special, with no possibility of such typo errors. For example in Python, myvar == None is incorrect, and should be written as myvar is None, so there's no more == to mistype.
Strictly speaking, although the null = myvar writing style will not protect you in all languages, it might protect you in some, so I'd have to admit it seems to be a good habit.
This is not true, they are the same.
I prefer the first one because i think it reads better.
if(myvar!=null)
if myvar is not equal to null
and
if(null!=myvar)
if null is not equal to myvar
There is no certain difference in both of them both refer to the same check
if(myvar!=null)
if(null!=myvar)
both are the exact same things.
But in depper context it is the Yoda Condition.
It is generally criticized because of its readability issues, so try to make every thing simple for yourself and for other people who might read your code as this is not a standard notation.
This is primary opinion based, but I always go with
if (variable == null)
if (variable != null)
because imo it´s a better programming style.
And a short answer to your post, no difference between them.
There is no practical difference in your case.
15.21. Equality Operators
The equality operators are commutative if the operand expressions have no side effects.
That is, you can have a situation where the LHS and RHS matter because evaluating them can cause a change in the other, but not if one of them is the keyword null.
Consider the following example:
public class Example {
static int x = 0;
public static void main(String[] args) {
System.out.println(doit() == x); // false
System.out.println(x == doit()); // true
}
static int doit() {
x++;
return 0;
}
}
Furthermore,
15.21.3. Reference Equality Operators == and !=
The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.
shows that there is no difference in the evaluation.
As Nitek wrote in the comment to my initial question:
The second one prevents typos like "myvar=null" because "null=myvar" won't compile. Might save you some trouble.
So, we have a BIG advantage of the second form - it helps to prevent serious logic error. Example:
Boolean i=false;
....
if(null=i){
}
won't compile
but
Boolean i=false;
....
if(i=null){
}
will
But the second form has a big disadvantage - it's reading difficulties.
So I would say that in 99% cases the first form is ok, but I prefer to use the second form. If you are sure you won't mix == and = up, use the first form. If not, use the second. I'm sure there are a couple of other cases when the second form is preferred, but can't remind it at the moment.

Is it bad to do Inner assignments?

We were having this discussion wiht my colleagues about Inner assignments such as:
return result = myObject.doSomething();
or
if ( null == (point = field.getPoint()) )
Are these acceptable or should they be replaced by the following and why?
int result = myObject.doSomething();
return result;
or
Point point = field.getPoint();
if ( null == point)
The inner assignment is harder to read and easier to miss. In a complex condition it can even be missed, and can cause error.
Eg. this will be a hard to find error, if the condition evaluation prevent to assign a value to the variable:
if (i == 2 && null == (point = field.getPoint())) ...
If i == 2 is false, the point variable will not have value later on.
if ( null == (point = field.getPoint()) )
Pros:
One less line of code
Cons:
Less readable.
Doesn't restrict point's scope to the statement and its code block.
Doesn't offer any performance improvements as far as I am aware
Might not always be executed (when there is a condition preceding it that evaluates to false.
Cons outweigh pros 4 / 1 so I would avoid it.
This is mainly concerned with readablity of the code. Avoid inner assignments to make your code readable as you will not get any improvements with inner assignments
Functionally Not Necessarily.
For Readability Definitely Yes
They should be avoided. Reducing the number of identifiers/operations per line will increase readability and improve internal code quality. Here's an interesting study on the topic: http://dl.acm.org/citation.cfm?id=1390647
So bottom line, splitting up
return result = myObject.doSomething();
into
result = myObject.doSomething();
return result;
will make it easier for others to understand and work with your code. At the same time, it wouldn't be the end of the world if there were a couple inner assignments sprinkled throughout your code base, so long as they're easily understandable within their context.
Well, the first one is not exactly inner assignment but in second case...it reduces readability ...but in some cases like below,
while ( null == (point = field.getPoint()) );
it's good to write it this way
In both cases the first form is harder to read, and will make you want to change it whenever you want to inspect the value in a debugger. I don't know how often I've cursed "concise" code when step-debugging.
There are a very few cases where inner assignments reduce program complexity, for example in if (x != null && y != null && ((c = f(x, y)) > 0) {...} and you really only need the assignment in the case when it is executed in the complex condition.
But in most cases inner assignments reduce readability and they easily can be missed.
I think inner assignments are a relict to the first versions of the C programming language in the seventies, when the compilers didn't do any optimizations, and the work to optimize the code was left to the programmers. In that time inner assignments were faster, because it was not necessary to read the value again from the variable, but today with fast computers and optimizing compilers this point doesn't count any more. Nevertheless some C programmers were used to them. I think Sun introduced inner assignments to Java only because they wanted to be similar to C and make it easy for C programmers to change to Java.
Always work and aim for code readability not writeability. The same goes for stuff like a > b ? x : y;
There are probably many developers out there not having issues reading your first code snipet but most of them are used to the second snipet.
The more verbose form also makes it easier to follow in a Debugger such as Eclipse. I often split up single line assignments so the intermediate values are more easily visible.
Although not directly requested by OP a similar case is function calls as method arguments may save lines but are harder to debug:
myFunction(funcA(), funcB());
does not show the return types and is harder to step through. It's also more error-prone if the two values are of the same type.
I don't find any harm in using inner assignments. It saves few lines of code (though im sure it doesn't improve compiling or execution time or memory). The only drawback is that to someone else it might appear cumbersome.

(a != null) or (null != a)

Is there any difference in comparing a variable with null or comparing the null with a variable?
For example, which comparation is better (a != null) or (null != a) ?
I've read somewhere that the second one is faster but didn't find the reason for this.
No, none is faster. That's a plain lie. There is no advantage of using the second version. Only making readability worse.
This all came from C, where you could erroneously write
if(x = 3)
instead of
if( x == 3)
Some people thought that it'd be best to write the constant first, in which case if you wrote =instead of ==, you'd get a compiler error. So some sources recommended writing
if(3 == x)
Some people didn't know why this was necessary and carried on and generalized this idea to constructs and languages where it makes absolutely no sense. IMO it didn't make a lot of sense in the original C context either, but that's a matter of personal taste.
Even if there were a difference in speed, I'd expect it to be entirely insignificant in 99.99% of apps. As it is, I wouldn't expect there to be any speed difference. Personally I find if (a != null) more readable - and readability is much more important than performance in most cases.
You might only want to use a literal before the variable when doing operations with strings.
if("abcd".equals(name)) doesn't throw a NPE where as if(name.equals("abcd")) does if at all name were to be null.
This is usually done to prevent accidental assignment instead of comparison:
( a = null ) //will not give error
( null = a ) //will give error
I'm fairly sure efficiency is not a reason, and if it were, an optimizer would render the code the same in binary.
No, there is no difference what so ever.
not really, not in java now anyways. in older days, may be C, you could accidentally forget the exclamation mark and the code would compile fine. basically, a = null would be taken as an expression that assigned null to a and always evaluate to true (because assignment was successful).
Today's compilers are far more robust. Although, old habits die hard and I still write null != a :-)

What is the value of the test !"".equals(someString)

In a project I've been trying to familiarise myself with, I ran across a method that looks like this:
public boolean testString(String string){
return string != null && !"".equals(string);
}
What is the value of testing the string for emptiness this way instead of with the variable first? I understand why we see constant-first (Yoda syntax) in C, but is there any reason to do so with method calls in Java?
note: I do understand about NullPointerException, which is not possible in this instance. I'm looking for a value to doing it this way in this case particularly.
In this context it makes little difference, as it already tested for null. Usually you do it this way to make sure you don't call a member on a null-reference (resulting in a NullPointerException), i.e.
"test".equals(myString)
will never throw a null pointer exception whereas
myString.equals("test")
will if myString is null. So basically, the first test makes sure it's a string (not null) AND it's equal to "test".
For two strings it doesn't matter much, but when there is a non-final type involved it can be a micro-optimization.
If the left hand side is a non-overridden concrete type, then the dispatch becomes static.
Consider what the JIT has to do for
Object o;
String s;
o.equals(s)
vs
s.equals(o)
In the first, the JIT has to find the actual equals method used, whereas in the second, it knows that it can only by String.equals.
I adopted the habit of doing
"constant value" == variableName
in other languages, since it means that the code will fail to parse if I mis-type = instead of ==.
And when I learned Java, I kept that order preference.
The usual reason for using "constant string".equals(variable) is that this works properly even if variable is null (unlike variable.equals("constant string")). In your case, however, since you are testing that string != null in a short-circuit boolean test, it's entirely a matter of style (or habit).
If they just did this:
!"".equals(string);
then they're avoiding the possibility of a NullPointerException, which is pretty smart. However, they're checking for null right before this condition, which is technically not necessary.
Is it running any tools like checkstyle? if it is, putting the variable first will result in checkstyle failing. Another reason is that if you put the empty string first it will take away the possibility of getting a null exception if the variable is null because the expression will always evaluate to false. If you had the variable first and the variable was null it will throw an exception.
It is more than a coder preference. If the purpose of the method was only to check that string is not an empty String (without caring whether its a null) then it makes sense to have the constant first to avoid a NullPointerException.
e.g. This method will return the boolean outcome. false in case string is null.
public boolean testString(String string){
return !"".equals(string);
}
while this one may throw a runtime exception if string is null
public boolean testString(String string){
return !string.equals("");
}
No, it is unnatural, and harder to read. It triggers a pause for most readers, and may wastefully consume lots of resources on stackoverlow.com.
(Better use string.isEmtpy() anyway)
There are no fixed rules tho, sometime this is easier to read
if( null != foobar(blahblahblah, blahblahblah, blahblahblah) )
than
if( foobar(blahblahblah, blahblahblah, blahblahblah) != null )
This question can be answered on a number of levels:
What does the example mean?
As other answers have explained, !"".equals(str) tests if str is an non-empty string. In general, the <stringLiteral>.equals(str) idiom is a neat way of testing a string that deals with the null case without an explicit test. (If str is null then the expression evaluates to false.
Is this particular example best practice?
In general no. The !"".equals(str) part deals with the case where str is null, so the preceding null test is redundant.
However, if str was null in the vast majority of cases, this usage would possibly be faster.
What is a better way to do this from a code-style perspective?
return "".equals(str);
or
return str != null && !str.isEmpty();
However, the second approach doesn't work with Java versions prior to 1.6 ... because isEmpty() is a recent API extension.
What is the optimal way to do this?
My gut feeling is that return str != null && !str.isEmpty(); will be fastest. The String.isEmpty() method is implemented as a one-line test, and is small enough that the JIT compiler will inline it. The String.equals(Object) method is a lot more complicated, and too big to be inlined.
Miško Hevery (see his videos on youtube) calls this type of overkill "paranoid programming" :-)
Probably in this video:
http://www.youtube.com/watch?v=wEhu57pih5w
See also here: http://misko.hevery.com/2009/02/09/to-assert-or-not-to-assert/

Categories