I have seen both of these when checking the equality of two Java String's:
// Method A
String string1;
// ...
if("MyString".equals(string1)) {
// ...
}
and
// Method B
String string1;
// ...
if(string1.equals("MyString")) {
// ...
}
My question is: which one is better and more widely used?
If you are sure that string1 can never be null then option 2 is readable and preferred. Otherwise option 1. Intention of option 1 is to avoid potential null pointer.
Method A won't throw a null pointer exception. There is no better of the two. It depends on whether on not you want it to throw a npe (and you might want that in your overall design).
Method B will fail with NullPointerException on null string1, whereas Method A will never throw this. Some authorities mandate this "defensive" programming. They have influenced me to do it, though it still does not come naturally!
It's also possible to write
if (string1 != null && string1.equals("MyString")) ...
though tools such as FindBugs flags this as a possible error, assuming that you should have made sure that string1 was already non-null. (Can you rely on the order of evaluation?).
So there are different schools of thought.
Method a does not throw NullPointerException and hence very convenient. It is widely used also.
Exceptions are for exceptional processing and have more overhead than checking for error conditions and handling them with regular logic. If you have been programming for a decade a NPE is a cringe matter which usually indicates careless code. Avoid them by using "constant".equals(variable) and people who read your code and use it will be happier.
The second one is more widely used. Neither is better.
It's the same idea as
if (1 == x)
but without a specific reason. but for a different reason. (Null pointer as noted by others).
Related
This question already has answers here:
object==null or null==object?
(11 answers)
Closed 7 years ago.
I have seen various codes of my seniors and they have used this at many places.What effect does it have? why cant they include anything != null. This is true for below thing too
"true".equals(x).
Why is this so?
anything != null is exactly equivalent to null != anything.
On the other hand, "true".equals(x) avoids the need to check if x is null when doing x.equals("true").
The reason for including constants on the left hand side of an equals expression is to avoid NullPointerException even when the variable is null. This also improves the readability of the expression.
That being said, null!=something is a personal choice and I would prefer using something!=null.
These are two separate practices.
Using null on the left side when comparing to null ensures that you won't, by mistake, use = instead of ==. However, this is a practice taken from languages other than Java, as in Java the expression
if ( something = null )
is going to fail as it does not resolve to a boolean value. In other languages it may be permissible to use a condition whose value is actually a pointer.
Thus this practice has no meaning in Java.
The second practice, as you were told, has to do with preventing a NullPointerException. It should be noted that this practice is controversial, because it allows a null to propagate to a later point in the program, and that usually means that it will be harder to find when it causes a bug.
This is called a Yoda condition. Among other things, it helps prevent an accidental assignment due to a missing = or !, as in foo = null. The reverse, null = foo, would not even compile.
That said, it is purely a stylistic preference. foo != null is logically equivalent to null != foo.
That check is so the program ensures the variable in question has been initialized before reading it. If a program tries to access a null variable, it will crash (specifically in Java it will throw a NullPointerException). It is a critical aspect of defensive programming.
As far as ordering, the evaluation of whether something is null or not is commutative. Meaning:
something != null
Is the same as
null != something
It is all a matter of personal preference. And as #manouti explains above, "true".equals(x) avoids the need to check if x is null when doing x.equals("true"), so you save a line of code.
Seems that some people prefer null != anything, because anything might be quite long expression, so writing null first makes it visible in the narrow window and simplifies code reading ("ok, we just check if something is not null"). But it's totally a matter of style.
As for "true".equals(x), it's well explained by #manouti.
This question already has answers here:
object==null or null==object?
(11 answers)
Closed 2 years ago.
Consider the following two lines of code
if (test ! = null)
and
if (null != test)
Is there is any difference in above two statements, performance wise? I have seen many people using the later and when questioned they say its a best practice with no solid reason.
No difference.
Second one is merely because C/C++ where programmers always did assignment instead of comparing.
E.g.
// no compiler complaint at all for C/C++
// while in Java, this is illegal.
if(a = 2) {
}
// this is illegal in C/C++
// and thus become best practice, from C/C++ which is not applicable to Java at all.
if(2 = a) {
}
While java compiler will generate compilation error.
So I personally prefer first one because of readability, people tend to read from left to right, which read as if test is not equal to null instead of null is not equal to test.
They are exactly the same. The second one can make sense when using equals:
if("bla".equals(test))
can never throw a NullPointerException whereas:
if(test.equals("bla"))
can.
There is no performance difference but I personally find the second one being confusing.
Second one looks for me like "Yoda condition", i.e. if(2 == x) ... and is much less readable.
It's best practice to avoid some basic typo's that most modern IDE's will pick up, because sometimes you want to do comparisons between more complex types that are not null and end up doing accidental assignments. So the pattern remains the same, but I've never seen this linked to performance and have never seen it generate special byte code.
The idea is to have the static, known value first, so you can't throw any kind of weird exception when you perform the comparison.
Neither of the two methods are "more correct" though, so it's entirely up to you to decide what you wish to use.
there is no difference. But in second way you avoid the typo like test = null. Beacause in second way you'll get compiler error.
It's not a best practice to use the latter one. Both are equivalent, but the former is easier to read.
This "best practice" comes from C where boolean don't exist. Integers are used instead, and if (foo = 1) is not a syntax error, but is completely different from if (foo == 1).
In Java, only boolean expressions can be inside an if, and this practice doesn't make much sense.
There is no really different between two form. There is no performance issue but there are following notes:
First form is readable for code reader, because people usually read codes Left-To-Right.
Second form is better for code writer, because in java = operator is for assignment and == operator is for test equivalent, but people usually using in if statement = instead of ==, by second approch developer getting Compile-Time-Error because null can't use in Left-Side of a assignment statement.
Every method accepts a set of parameter values. Should we always validate the non-nullness of input parameters or allow the code to fail with classic RunTimeException?
I have seen a lot of code where people don't really check the nullness of input parameters and just write the business logic using the parameters. What is the best way?
void public( String a, Integer b, Object c)
{
if( a == null || b == null || c == null)
{
throw new RunTimeException("Message...");
}
.....business logic.....
}
The best way is to only check when necessary.
If your method is private, for example, so you know nobody else is using it, and you know you aren't passing in any nulls, then no point to check again.
If your method is public though, who knows what users of your API will try and do, so better check.
If in doubt, check.
If the best you can do, however, is throw a NullPointerException, then may not want to check. For example:
int getStringLength(String str) {
return str.length();
}
Even if you checked for null, a reasonable option would be throwing a NullPointerException, which str.length() will do for you anyways.
No. It's standard to assume that parameters will not be null and that a NullPointerException will be thrown otherwise. If your method allows a parameter to be null, you should state that in your api.
It's an unfortunate aspect of Java that references can be null and there is no way to specify in the language that they are not.
So generally yes, don't make up an interpretation for null and don't get into a situation where an NPE might be thrown later.
JSR305 (now inactive) allowed you to annotate parameters to state that they should not be given nulls.
void fn(#Nonnull String a, #Nonnull Integer b, #Nonnull Object c) {
Verbose, but that's Java for you. There are other annotation libraries and checkers that do much the same, but are non-standard.
(Note about capitalisation: When camel-casing words of the form "non-thing", the standard is not to capitalise the route word unless it is the name of a class. So nonthing and nonnull.)
Annotations also don't actually enforce the rule, other than when a checker is run. You can statically include a method to do the checking:
public static <T> T nonnull(T value) {
if (value == null) {
throwNPE();
}
return value;
}
private static void throwNPE() {
throw new NullPointerException();
}
Returning the value is handy in constructors:
import static pkg.Check.nonnull;
class MyClass {
#Nonnull private final String thing;
public MyClass(#Nonnull String thing) {
this.thing = nonnull(thing);
}
...
I don't see a great deal of point in doing this. You're simply replicating behaviour that you'd get for free the first time you try to operate on a, b or c.
It depends if you expect any of your arguments to be null - more precisely, if your method can still make a correct decision if some parameters are null.
If not, it's good practice to check for null and raise an exception, because otherwise you'll get a NullPointerException, which you should never catch, as its appearance always indicates that you forgot to check your variables in your code. (and if you catch it, you might miss other occurrences of it being thrown, and you may introduce bugs).
On the other hand, if you throw RunTimeException or some other custom exception, you could then handle it somewhere on the upstream, so that you have more control over what goes on.
Yes, public methods should scrub the input, especially if bad input could cause problems within your method's code. It's a good idea to fail fast; that is, check as soon as possible. Java 7 added a new Objects class that makes it easy to check for null parameters and include a customized message:
public final void doSomething(String s)
{
Objects.requireNonNull(s, "The input String cannot be null");
// rest of your code goes here...
}
This will throw a NullPointerException.
Javadocs for the Objects class: http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html
It depends on what your code is trying to do and the situation in which you want to throw an Exception. Sometime you will want your method to always throw an Exception if your method will not be able to work properly with null values. If your method can work around null values then its probably not necessary to throw an Exception.
Adding too many checked Exceptions can make for very convoluted and complicated code. This was the reason that they were not included in C#.
No, you shouldn't do that universally.
My preferences, in order, would be:
Do something sensible with the null. The sensible thing to do depends entirely on the situation, but throwing a custom exception should not be your first choice.
Use an assertion to check for null and test thoroughly, eliminating any situations in which null input is produced since - a.k.a bugs.
For public APIs, document that null isn't allowed and let it fail with an NPE.
You should never throw a runtime exception unless it is truly a fatal condition for the operation of the system, such as missing critical runtime parameters, but even then this is questionable as the system should just not start.
What are the business rules? Is null allowed for the field? Is it not?
In any case, it is always good practice to CHECK for nulls on ANY parameters passed in before you attempt to operate on them, so you don't get NullPointerExceptions when someone passes you bad data.
If you don't know whether you should do it, the chances are, you don't need to do it.
JDK sources, and Joshua Bloch's book, are terrible examples to follow, because they are targeting very different audiences. How many of us are writing public APIs for millions of programmers?
I'm reviewing a manual of best practices and recommendation coding java I think is doubtful.
Recomendation:
String variable;
"xx".equals(variable) // OK
variable.equals("xx") //Not recomended
Because prevents appearance of NullPointerException that are not controlled
Is this true?
This is a very common technique that causes the test to return false if the variable is null instead of throwing a NullPointerException. But I guess I'll be different and say that I wouldn't regard this as a recommendation that you always should follow.
I definitely think it is something that all Java programmers should be aware of as it is a common idiom.
It's also a useful technique to make code more concise (you can handle the null and not null case at the same time).
But:
It makes your code harder to read: "If blue is the sky..."
If you have just checked that your argument is not null on the previous line then it is unnecessary.
If you forgot to test for null and someone does come with a null argument that you weren't expecting it then a NullPointerException is not necessarily the worst possible outcome. Pretending everything is OK and carrying until it eventually fails later is not really a better alternative. Failing fast is good.
Personally I don't think usage of this technique should be required in all cases. I think it should be left to the programmer's judgement on a case-by-case basis. The important thing is to make sure you've handled the null case in an appropriate manner and how you do that depends on the situation. Checking correct handling of null values could be part of the testing / code review guidelines.
It is true. If variable is null in your example,
variable.equals("xx");
will throw a NPE because you can't call a method (equals) on a null object. But
"xx".equals(variable);
will just return false without error.
Actually, I think that the original recommendation is true. If you use variable.equals("xx"), then you will get a NullPointerException if variable is null. Putting the constant string on the left hand side avoids this possibility.
It's up to you whether this defense is worth the pain of what many people consider an unnatural idiom.
This is a common technique used in Java (and C#) programs. The first form avoids the null pointer exception because the .equals() method is called on the constant string "xx", which is never null. A non-null string compared to a null is false.
If you know that variable will never be null (and your program is incorrect in some other way if it is ever null), then using variable.equals("xx") is fine.
It's true that using any propertie of an object that way helps you to avoid the NPE.
But that's why we have Exceptions, to handle those kind of thing.
Maybe if you use "xx".equals(variable) you would never know if the value of variable is null or just isn't equal to "xx". IMO it's best to know that you are getting a null value in your variable, so you can reasign it, rather than just ignore it.
You are correct about the order of the check--if the variable is null, calling .equals on the string constant will prevent an NPE--but I'm not sure I consider this a good idea; Personally I call it "slop".
Slop is when you don't detect an abnormal condition but in fact create habits to personally avoid it's detection. Passing around a null as a string for an extended period of time will eventually lead to errors that may be obscure and hard to find.
Coding for slop is the opposite of "Fail fast fail hard".
Using a null as a string can occasionally make a great "Special" value, but the fact that you are trying to compare it to something indicates that your understanding of the system is incomplete (at best)--the sooner you find this fact out, the better.
On the other hand, making all variables final by default, using Generics and minimizing visibility of all objects/methods are habits that reduce slop.
If you need to check for null, I find this better readable than
if (variable != null && variable.equals("xx")). It's more a matter of personal preference.
As a side note, here is a design pattern where this code recommendation might not make any difference, since the String (i.e. Optional<String>) is never null because of the .isPresent() call from the design pattern:
Optional<String> gender = Optional.of("MALE");
if (gender.isPresent()) {
System.out.println("Value available.");
} else {
System.out.println("Value not available.");
}
gender.ifPresent(g -> System.out.println("Consumer: equals: " + g.equals("whatever")));
I’m from a .NET background and now dabbling in Java.
Currently, I’m having big problems designing an API defensively against faulty input. Let’s say I’ve got the following code (close enough):
public void setTokens(Node node, int newTokens) {
tokens.put(node, newTokens);
}
However, this code can fail for two reasons:
User passes a null node.
User passes an invalid node, i.e. one not contained in the graph.
In .NET, I would throw an ArgumentNullException (rather than a NullReferenceException!) or an ArgumentException respectively, passing the name of the offending argument (node) as a string argument.
Java doesn’t seem to have equivalent exceptions. I realize that I could be more specific and just throw whatever exception comes closest to describing the situation, or even writing my own exception class for the specific situation.
Is this the best practice? Or are there general-purpose classes similar to ArgumentException in .NET?
Does it even make sense to check against null in this case? The code will fail anyway and the exception’s stack trace will contain the above method call. Checking against null seems redundant and excessive. Granted, the stack trace will be slightly cleaner (since its target is the above method, rather than an internal check in the HashMap implementation of the JRE). But this must be offset against the cost of an additional if statement, which, furthermore, should never occur anyway – after all, passing null to the above method isn’t an expected situation, it’s a rather stupid bug. Expecting it is downright paranoid – and it will fail with the same exception even if I don’t check for it.
[As has been pointed out in the comments, HashMap.put actually allows null values for the key. So a check against null wouldn’t necessarily be redundant here.]
The standard Java exception is IllegalArgumentException. Some will throw NullPointerException if the argument is null, but for me NPE has that "someone screwed up" connotation, and you don't want clients of your API to think you don't know what you're doing.
For public APIs, check the arguments and fail early and cleanly. The time/cost barely matters.
Different groups have different standards.
Firstly, I assume you know the difference between RuntimeExceptions (unchecked) and normal Exceptions (checked), if not then see this question and the answers. If you write your own exception you can force it to be caught, whereas both NullPointerException and IllegalArgumentException are RuntimeExceptions which are frowned on in some circles.
Secondly, as with you, groups I've worked with but don't actively use asserts, but if your team (or consumer of the API) has decided it will use asserts, then assert sounds like precisely the correct mechanism.
If I was you I would use NullPointerException. The reason for this is precedent. Take an example Java API from Sun, for example java.util.TreeSet. This uses NPEs for precisely this sort of situation, and while it does look like your code just used a null, it is entirely appropriate.
As others have said IllegalArgumentException is an option, but I think NullPointerException is more communicative.
If this API is designed to be used by outside companies/teams I would stick with NullPointerException, but make sure it is declared in the javadoc. If it is for internal use then you might decide that adding your own Exception heirarchy is worthwhile, but personally I find that APIs which add huge exception heirarchies, which are only going to be printStackTrace()d or logged are just a waste of effort.
At the end of the day the main thing is that your code communicates clearly. A local exception heirarchy is like local jargon - it adds information for insiders but can baffle outsiders.
As regards checking against null I would argue it does make sense. Firstly, it allows you to add a message about what was null (ie node or tokens) when you construct the exception which would be helpful. Secondly, in future you might use a Map implementation which allows null, and then you would lose the error check. The cost is almost nothing, so unless a profiler says it is an inner loop problem I wouldn't worry about it.
In Java you would normally throw an IllegalArgumentException
If you want a guide about how to write good Java code, I can highly recommend the book Effective Java by Joshua Bloch.
It sounds like this might be an appropriate use for an assert:
public void setTokens(Node node, int newTokens) {
assert node != null;
tokens.put(node, newTokens);
}
Your approach depends entirely on what contract your function offers to callers - is it a precondition that node is not null?
If it is then you should throw an exception if node is null, since it is a contract violation. If it isnt then your function should silently handle the null Node and respond appropriately.
I think a lot depends on the contract of the method and how well the caller is known.
At some point in the process the caller could take action to validate the node before calling your method. If you know the caller and know that these nodes are always validated then i think it is ok to assume you'll get good data. Essentially responsibility is on the caller.
However if you are, for example, providing a third party library that is distributed then you need to validate the node for nulls, etcs...
An illegalArugementException is the java standard but is also a RunTimeException. So if you want to force the caller to handle the exception then you need to provided a check exception, probably a custom one you create.
Personally I'd like NullPointerExceptions to ONLY happen by accident, so something else must be used to indicate that an illegal argument value was passed. IllegalArgumentException is fine for this.
if (arg1 == null) {
throw new IllegalArgumentException("arg1 == null");
}
This should be sufficient to both those reading the code, but also the poor soul who gets a support call at 3 in the morning.
(and, ALWAYS provide an explanatory text for your exceptions, you will appreciate them some sad day)
like the other : java.lang.IllegalArgumentException.
About checking null Node, what about checking bad input at the Node creation ?
I don't have to please anybody, so what I do now as canonical code is
void method(String s)
if((s != null) && (s instanceof String) && (s.length() > 0x0000))
{
which gets me a lot of sleep.
Others will disagree.