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/
Related
I have a getter that returns a String and I am comparing it to some other String. I check the returned value for null so my ifstatement looks like this (and I really do exit early if it is true)
if (someObject.getFoo() != null && someObject.getFoo().equals(someOtherString)) {
return;
}
Performancewise, would it be better to store the returned String rather than calling the getter twice like this? Does it even matter?
String foo = someObject.getFoo();
if (foo != null && foo.equals(someOtherString)) {
return;
}
To answer questions from the comments, this check is not performed very often and the getter is fairly simple. I am mostly curious how allocating a new local variable compares to executing the getter an additional time.
It depends entirely on what the getter does. If it's a simple getter (retrieving a data member), then the JVM will be able to inline it on-the-fly if it determines that code is a hot spot for performance. This is actually why Oracle/Sun's JVM is called "HotSpot". :-) It will apply aggressive JIT optimization where it sees that it needs it (when it can). If the getter does something complex, though, naturally it could be slower to use it and have it repeat that work.
If the code isn't a hot spot, of course, you don't care whether there's a difference in performance.
Someone once told me that the inlined getter can sometimes be faster than the value cached to a local variable, but I've never proven that to myself and don't know the theory behind why it would be the case.
Use the second block. The first block will most likely get optimized to the second anyway, and the second is more readable. But the main reason is that, if someObject is ever accessed by other threads, and if the optimization somehow gets disabled, the first block will throw no end of NullPointerException exceptions.
Also: even without multi-threading, if someObject is by any chance made volatile, the optimization will disappear. (Bad for performance, and, of course, really bad with multiple threads.) And lastly, the second block will make using a debugger easier (not that that would ever be necessary.)
You can omit the first null check since equals does that for you:
The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
So the best solution is simply:
if(someOtherString.equals(someObject.getFoo())
They both look same,even Performance wise.Use the 1st block if you are sure you won't be using the returned value further,if not,use 2nd block.
I prefer the second code block because it assigns foo and then foo cannot change to null/notnull.
Null are often required and Java should solve this by using the 'Elvis' operator:
if (someObject.getFoo()?.equals(someOtherString)) {
return;
}
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.
I came across these two ways of having a null check for a string object.
Given a string object String str = "example";
If(str.someMethod() != null ) or
If (null != str.someMethod())
Why do we prefer the 2nd one ?
What is the exact reason behind this, is it related to performance ?
In your example, it makes absolutely no difference which you do (other than style), because the reason for Yoda checks is to avoid accidentally doing an assignment (but keep reading for why this doesn't matter in Java), and you can't assign to the result of calling a method.
One of the nice things about Java is that even if you were testing str, e.g.:
if (str == null)
vs.
if (null == str)
there would still be no difference, whereas in some of the languages with syntax derived from B (such as C, C++, D, JavaScript, etc.), people do the second (a "Yoda test") to minimize the odds of this bug:
if (str = null) // Not an issue in Java
In C or JavaScript, for instance, that would assign null to str, then evaluate the result, coerce it to boolean, and not branch. But in Java, that's a syntax error the compiler tells you about.
Java doesn't do that kind of boolean conversion, so the only reason for using Yoda checks in Java is if you're testing booleans, e.c.
boolean flag;
// ...
if (flag == false)
There, you might conceivably do this by accident:
if (flag = false)
But since using == and != with booleans is completely unnecessary (you'd just use if (flag) or if (!flag)), in the real world you don't need Yoda checks with Java at all.
That doesn't mean people don't still use them, as a matter of their own personal style. There's just no objective reason to, in Java.
It makes no difference performance-wise, however the Yoda programming pattern have some advantages when it comes to the world of programming skills.
In your example it would not matter as both cases would throw a NullPointerException (since you're invoking someMethod` of a null instance reference).
However, say that you wanted to check if str is null. In the first case, you'd write if (str == null) and in the second if (null == str). Both are the same. Now say that you have accidently used = instead of ==. In Java, it would not matter as the compiler wouldn't let you as the expression doesn't evalute to a boolean value. But other languages let you do that, more specifically languages that are compiler-free and only use an interperter. In that case, if you write if (str = null) you'll be assigning null to string and overriding its' current value, which would result in buggy behavior and you chasing after your tail for quite some time. However, if you'd write if (null = str) you'll get an error saying you cannot assign a value to null and thus save yourself a lot of time and effort. Again, this is not relevant to JAVA.
An example which might be relevant for Java, is the use of method invocation on constant values. For example, if (str.equals("constantString"). If str is null you'll get a NullPointerException. However, if you use a Yoad pattern and write if ("constantString".equals(str)) you'll get false as ConstantString does not equal null. This of course is only relevant for comparison, and not say contains etc.
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.
I asked this goofy question earlier today and got good answers. I think what I really meant to ask is the following:
String aString = ""; // Or = null ?
if(someCondition)
aString = "something";
return aString;
In this case, the string has to be initialized in order to return it. I always thought that either option (setting it to "" or to null looks kind of ugly. I was just wondering what others do here...or is it more of just a matter of whether you want empty string or null being passed around in your program (and if you are prepared to handle either)?
Also assume that the intermediary logic is too long to cleanly use the conditional (? :) operator.
return (someCondition) ? "something" : "";
or
return (someCondition) ? "something" : null;
Typically though if your function says it will return a String I prefer to actually return a String instead of a null. Either way the calling function should probably check for both cases.
depends on what you want to achieve,
in general i would return null to signal that nothing was processed,
it might later pop up cases where someCondition is true but the string you build together is "" anyway, that way you can differentiate from that case if you return null if nothing was processed.
i.e.
String aString = null;
if(someCondition)
aString = "something";
return aString;
but it all really depends on what you want to achieve...
e.g. if the code is suppose to build together a string that is delivered directly in the UI you would go for "" instead
In this case it might be best to do something like:
public void func() {
boolean condition = getConditionFromSomewhere();
String condString = getAppropriateValue(condition);
}
public String getAppropriateValue(boolean condition) {
if (condition) {
return "something";
} else {
return "somethingElse";
}
}
It may seem a bit overkill for a boolean condition, but if you get into more complex conditions (more choices, like enums and the like), it would nicely abstract that logic away. And with a descriptive method name make it almost self-documenting to boot.
Since you're asking our opinions...
I'm a bit overconscious about quality. I prefer that all my "if" statements have an "else", because (1) it helps to understand the code if there are multiple nested "if's", (2) force me to consider the possibility (what should happen if the condition is false?).
Regarding reason (1), I prefer to avoid nested if's, but sometimes you inherit code with a lot of if's.
if(someCondition)
aString = "something";
else
aString = "";
I would prefer "null", because it would make the app fail and dump a stack that I can follow. An empty string, in contrast, would keep things going. Naturally, it depends on the logic of your code what is better: null or "".
Yes, this is just a matter of whether you want a null or an empty string being passed around in your program. If you plan to append things to it later, and the someCondition just indicates that you should give it a first value to begin with, then use the empty string. If you plan to have it indicate that there is a string or there is nothing, then perhaps using null is better.
Its just your preference of what your api should do. If you are returning null, there may be a chance that the api users can get NPE if they are not checking for null. But if you are using "" string, the error may pass silently if it is not supposed to be null. It is a preference of how you write your api and depends on the use case.
Thinking about it, I rarely use "" in code for any purpose.