Is returning null a good idea? [duplicate] - java

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)

Related

Why use Optional.of method if a missing value is not permitted per business logic [duplicate]

This question already has answers here:
Uses for Optional
(14 answers)
Closed 1 year ago.
Instead of initialising optCar variable as below:
Optional<'Car'> optCar = Optional.of(car);
Why not initialise it simply as :
Car optCar = car;
When a business logic does not permit car to be null?
You totally can.
Optional is for situations where you would have a code
If(object == null) {…
Instead you use Optional and then you have cool access to stream like features and or/or else statements that make ur code so much nicer, for example:
return Optional.ofNullable(object).orElse(defaultObject);
Or another example
return Optional.ofNullable(object).map(Object::toString).orElseThrow();
This last code return string representation of ur object if that optional is present or else throws an exception. orElseThrow is most useful in situations where you actually are sure that object is always there so such situation will likely never arise and if it does u know where to look.
But like I said in the beginning if you don’t need these features u don’t need to use it
if you are sure that car can never be null then using Optional would be an overkill.
The presence of Optional is to provide for clarity that this particular instance can be null and the Optional needs to be unwrapped and explicitly checked for the absence (or presence) of a value.
Do not go by what I say, hear it from the expert:
Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors.
Excerpted from Brian Goetz's answer here.

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.

Lazy evaluation not working as it should

I had to evaluate a boolean expression frecuently, so I converted it in a private method in it's class. Here is the code it's causing me trouble:
//"x", "y" and "team" are already defined
return (map.isWalkable(x,y) &&
(!map.isOccupied(x,y) || map.getOccupant(x, y).getTeam() == team) );
Methods should be preety much self-explanatory as for the purpose of this question. Now, isWalkable and isOccupied both return a boolean, and getOccupant is the only method returning an object reference. The problem is that I'm getting a NullPointerException when executing this piece of code, and that shouldn't be happening because isOccupied returns true if and only if map.getOccupant != null (that's actually what that method returns). So with a language supporting lazy boolean evaluation from left to right (as I assume java is, or at least that's what I was able to read) the getOccupant method should never be executed whenever it would return null am I right?
Is this more compiler-dependent than I thought it was? Should it be safer if I used if statements, or is there simply something obvious I'm missing here, maybe operations get resolved the other way round.
The issue is your parenthesis. Try
return (map.isWalkable(x,y) && (!map.isOccupied(x,y) || map.getOccupant(x, y).getTeam() == team));
Simply put, no, lazy evaluation is not broken. Your code is.
Either map is null, or map.getOccupant(x,y) returns null.
If you put them on their own lines and go through them with a debugger, you'll notice that "oh no, I was so stupid and didn't notice that".
The compiler, JVM or anything else has nothing to do with this.

Null check coding standard [duplicate]

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.

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