Null check coding standard [duplicate] - java

This question already has answers here:
Which has better performance: test != null or null != test [duplicate]
(8 answers)
Closed 9 years ago.
I have a doubt regarding coding standard of a null check.
I want to know the difference between
if(a!=null)
and
if(null!=a)
which one is better,which one to use and why?

Both are same in Java, as only boolean expressions can be inside an if. This is just a coding style preference by programmer and most of them use null != a.
The null != a is an old practice in programming languages like Java,C++ (called as Yoda Conditions).
As it is valid to write if (a = null) and accidentally assign null to the a so writing null first is a guard to stop this accident from happening.

There is no difference. But the first is more common. The second is also called "Yoda Conditions" because of its unnatural "grammar".
Once I was working in a project where the coding guideline was to use if (null != a) because they thought it is easier for the developer to understand that the constant value has to come first always (as in CONSTANT_VALUE.equals(variable). That was pretty annoying to me.

They're both the same. It depends on your coding style.

From the compiler's point of view, they're exactly the same. But the first form is more readable, so I'd advise you to use that one.

No difference betwwen them if statement works based on result of expression
so u write either if(a!=null) or if(null!=a) will produce true or false then result is evaluated.
So it doesnt matter you write which you like

They both are same. Although the first variant is common the second variant is useful if you know the first variable is not null
Example "some value".equals(your_variable) , some value can be any value you know is not null. This will avoid NPE when your_variable is null.
String str = "somevalue";
if(str != null && str.equals("somevalue")) { }
if("somevalue".equals(str)) { }
Both the conditions will be same if str is null or not.

Related

Difference between if(object == null) v if(null == object)? [duplicate]

This question already has answers here:
object==null or null==object?
(11 answers)
Closed 4 years ago.
What is the difference between the two? Which one is better? I was asked this in an Interview.
The only difference I can think of is that if you wanted to do if(null == object) and forgot to add == and added =, it will not have any side-effect to your program. But if you do this mistake while doing if(object = null) then your program is toast.
Adding to Nayuki's answer, if the programmer mistypes = for ==, like if (object = null), there are still few cases where compilation error won't come and bugs would creep in the code.
For example: if (boolean1 = boolean2), is an assignment expression first and then is evaluated for the if condition. Another problematic code is if (wrapperBool = null), where wrapperBool is a Boolean wrapper class variable. It will throw a NullPointerException (NPE) at runtime.
But as Benny mentioned, mistyping should be caught upfront with unit test case(s).
In the Java programming language, the two expressions if (object == null) versus if (null == object) do exactly the same thing, because the == operator is commutative. The former notation is considered more natural when spoken in English, whereas the latter notation has some proponents.
If the programmer mistypes = for ==, like if (object = null), this is a compile-time error in Java because the condition expression must be a boolean value, not Object. Hence, if (object == null) and if (null == object) are equally secure against typos in Java.
But in C and C++, integer, floating-point, and pointer types are implicitly coerced to bool in a condition expression. Writing if (object = null) will compile but do the wrong thing, whereas writing if (null = object) should trigger a compile-time error.
See also: https://coderanch.com/t/489740/java/difference-null-object-object-null
Because of its commutative property, the only difference between object == null and null == object (the Yoda version) is of cognitive nature: how the code is read and digested by the reader. I don't know the definitive answer though, but I do know I personally prefer comparing the object I'm inspecting to something else, rather than comparing something else to the object I'm inspecting, if that makes any sense. Start with the subject, then the value to compare it to.
In some other languages this comparison style is more useful.
To safe guard against a missing "=" sign in general though, I think writing null == object is a misguided act of defensive programming. The better way around this particular code is by guaranteeing the behavior with a junit test. Remember, the possible mistake of missing an "=" is not dependant on the method's input arguments - you are not dependent on the right use of this API by other people - so a junit test is perfect to safe guard against that instead. Anyway you will want to write junit tests to verify the behavior; a missing "=" naturally falls within scope.
Or maybe, could it have been a trick question to get you on the topic of discussing the uses of Optional to avoid raw null-checks altogether?

why use null != anything instead of anything!=null? [duplicate]

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.

Is returning null a good idea? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is returning null bad design?
Suppose I have a prompt asking the user to enter something. If the user does not match my specifications, the else block returns null. Is this bad practice? If so, how could I repeat the prompt within the scope of the if/else block?
if( foo.equalsIgnoreCase( "y" ) ) {
return bar[x][y];
}
else if( foo.equalsIgnoreCase( "n" ) ) {
return bar[x++][y];
}
else {
return null;
}
null is a fine value to use for this purpose. It's not a bad practice. You need to use something, and null has "not defined" semantics.
Your other option is to return what the user entered, and then test "if its not 'y' or its not 'n' then ask again", but really, thats more complicated that just testing something like !value.
Just be sure to document that your method "will return null if user does not enter 'y' or 'n'" in the javadocs.
null as a return value is certainly not bad practice. Whether or not it's the right choice in your case depends on the method, and the rest of the class interface.
I believe it would be better to define a constant representing this 3rd option.
Your source code will be easier to read.
If you want to set it to null that's fine, but I would recommend against it, since this opens you up to the possibility of NullPointerException problems later down the line.
For this reason I consider returning null poor practice in many circumstances.
You can read more about this here: https://stackoverflow.com/a/1274822/383414 (someone flagged this question as a possible duplicate)

Which has better performance: test != null or null != test [duplicate]

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.

what is the standard guideline to declare the "==" condition? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)?
please see the below code:-
if(myVariable==5)
{
//some logic
}
one of my friends says that this is not a good way to write the code as its not per guidelines, however he dont have any reason to it. Is there is a chance of exception with above code or accidental modification?? According to him the better way would have been
if(5==myVariable)
{
//some logic
}
please let me know which is a better way and why??? Do provide links if u have any.
The only reason to write:
5 == variable
instead of
variable == 5
is that in the former case if you incorrectly put an assignment (single =) in place you will get a compile time error because you are trying to overwrite a constant.
However any decent compiler will give you a warning if you do:
if (variable = 5)
so IMHO it's not worth worrying about. I always use the latter if (var == num) form.
However in Java there is a common pattern that is worth using. When testing a string for equality, one should use:
if ("constant".equals(variable)) { ... }
instead of:
if (variable.equals("constant")) { ... }
since the latter can trigger a null pointer exception, and the former cannot.
The reversal is preferable in some languages like C, where
if (x = 5) {
...
}
would accidentally assign x to the value 5 if you mistype = instead of ==. By reversing the two arguments the compiler would rightfully object to you reassigning the value 5.
Unlike C/C++, for languages such as Java it's not such an issue since
if (x = 5) {
...
}
isn't a valid statement. I still follow the above practise however. I don't have to rethink when swapping between Java and C/C++.
Both are same. select which ever you find more readable.. I would go with first
For that specific case, it's technically safer to do 5 == variable because then if you accidentally say 5 = variable the compiler will complain. On the other hand, variable = 5 is perfectly legal.
This convention is to prevent you from accidentally writing if (myVariable=5) when you mean if (myVariable==5).
For ==, it doesn't matter a bit what order you do it in.
Your friend mentioned "guidelines"-- perhaps it's a business rule? Albeit an arbitrary and semi-pointless one...
It's immaterial. I prefer the first one, because it's more readable.
I hope you're aware that using == is not always correct for reference types. In those cases you should prefer equals. THEN it matters, because you want to avoid null pointer exceptions. It's best to dereference the instance that cannot be null in that case.
There is no such guildline I found.
First approach should be followed because it is more readable.
i think if you what to know if they are equals it's fine then.
but if you want to know about string, then i more appropriated use '.equals'.
e.g:
object.equals("something");
The only thing I can think of is to avoid possible syntax errors of the kind constant = expression, or to avoid mangled operator overload in C++. In Java both expressions are syntatically valid and picking one over the other is a matter of choice.

Categories

Resources