Since myObject.toString() fails when myObject is null (throws a NullPointerException), it is safer to do myObject+"", since it's essentially doing String.valueOf(myObject).concat(""), which doesn't fail, but would instead result in the String "null".
However, is this a good practice? My first thought is that it seems like it might take longer to perform, since it's implicitly calling two methods, but it does help guarantee software that doesn't crash.
You certainly can do myObject+"". But as you already know, that requires some extra method invocation. That will depend upon the application you're using it in. Will that extra method invocation be a bottle-neck for the application? I guess that is rarely an issue. Or, to avoid that extra method call, you can directly use String#valueOf() method. But that would depend upon how you want to handle nulls. I would certainly not proceed normally in these circumstances. At least log a message indicating null reference.
Also, if you're already on Java 7, then you can use Objects.toString(Object) method, that handles null for you. Again, that method returns "null" for null references.
So, now it's your call. I've given you some option. You might want to throw exception, log message and proceed with "null" string, or some default string like "".
If you want that behavior, String.valueOf(myObject) gets you the same while being less hacky. But it also means that a null string and the string "null" are treated the same. It's usually better to check for null values explicitly, unless you're just print to a log or such. But in those cases, most methods take an Object reference and handle nulls for you (e.g. System.out.println, most logging frameworks, etc.)
Related
First of all, I know the difference between the two methods.
Optional.of : Used to ensure that there is no null, if null is entered, nullPointExcepction
Optional.ofNullable : may or may not be null. Used to respond flexibly.
So, if I add orElseThrow(() -> new NullPointerException("null data")) to this, will it end up being the same?
I want to throw an error with explicit content.
So I get Optional.ofNullable(data).orElseThrow(() -> new NullPointerException("null data")))
use it as Is this pointless behaviour?
Optional.of(data).orElseThrow(() -> new NullPointerException("null data")))
I think this is also possible, but I'm just using ofNullable() to make the code look consistent.
to sum it up,
In the end, if you add orElseThrow(nullPoint)
Are of or ofNullable the same result?
then rather
Is of.orElseThrow better?
to sum it up, In the end, if you add orElseThrow(nullPoint) Are of or ofNullable the same result?
No. To see this, simply look at the types.
public static <T> Optional<T> of(T value);
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
throws X extends Throwable;
Optional.of returns an Optional<T>, where orElseThrow is going to leave you with a T. So Optional.ofNullable(x).orElseThrow(...) is really just a very roundabout
if (x == null) {
throw new NullPointerException(...);
}
You're not actually doing anything with the Optional, just making one and discarding it in a really verbose way. So if that's your intent, just do an explicit null check; there's no need at all for Optional.
Which raises the question of why we would use of or ofNullable. With the introduction of Optional, there are now two ways to represent the concept of "this value might not exist" in Java: null and Optional.empty(). People on the Internet will argue till the end of time about which is better and when you should use which one (I have strong opinions on this which I'll refrain from sharing here, since it's not what you asked), but the point is that there are two different ways to do it.
For the rest of this post, I'll borrow a bit of notation from Kotlin and write T? to mean "a T value which might be null". It's not valid Java notation, but it gets the point across. So if we want to represent "A T which may or may not exist" in Java, we can use either Optional<T> or T?.
If we want to go from T? to Optional<T>, that's what Optional.ofNullable is for. It says "If the thing is null, give me Optional.empty(); otherwise give me the thing in an Optional". To go the other way, we can use Optional.orElse(null), which says "If I have a T, give it to me, otherwise show me null". So now we have a way to convert between the two approaches. So what's Optional.of for?
You should view Optional.of as an assertion of sorts. If Java had nullable types like Kotlin, then the difference would be something like
public static <T> Optional<T> of(T value);
public static <T> Optional<T> ofNullable(T? value);
That is, ofNullable expects that its value might be null. of is already assuming that it's not. Optional.of should be thought of an assertion that the value you're giving it is not null. If that assertion fails, we throw NullPointerException immediately rather than letting errors propagate to other parts of the program. If you're calling Optional.of and recovering from the NullPointerException it throws[1], then you are doing something very wrong. That function is an assertion we were dealing with non-null data to begin with, and if that assertion fails then your program should fail immediately with a good stack trace.
It sounds like, based on your use case, you have a value that might be null. In that case, Optional.ofNullable makes sense; it's prepared to handle the use case. If you want to throw a custom exception, you should do a null check beforehand (since you're the one handling the null, not Optional) and then call Optional.of. Or, of course, you can just do an old-fashioned null check and not use Optional at all, if you're planning to extract it anyway with orElseThrow. Certainly, the pipeline Optional.ofNullable(value).orElseThrow(...) in one line would be a code smell.
[1] Note that I say "recovering from", not "catching". A nice top-level catch (Exception exc) which logs all errors is perfectly acceptable and generally a good idea in larger applications. But if you're doing catch (NullPointerException exc) { return 0; } or something like that then you need to reconsider which Optional method you should be using.
First of all, I know the difference between the two methods.
Optional.of : Used to ensure that there is no null, if null is
entered, nullPointExcepction
Optional.ofNullable : may or may not be null. Used to respond
flexibly.
There's a clear point of misunderstanding.
The purpose of Optional.of() is not "to ensure that there is no null". It is not meant to be used as an assertion that a value that was passed into it is non-null. For such a validation you can use Objects.requireNonNull(), it'll either throw an NPE, or will return you a non-null value.
In order to be on the same page, the first important thing you have to keep in mind is that optionals were introduced in the JDK for only one particular purpose - to serve as a return type. Any other cases when optional is utilized as a parameter-type, or a field-type, or when optional objects are being stored in a collection isn't considered to be a good practice. As well, as creating an optional just in order to chain methods on it or to hide a null-check is considered to be an antipattern.
Here is a couple of quotes from the answer by #StuartMarks, developer of the JDK:
The primary use of Optional is as follows:
Optional is intended to
provide a limited mechanism for library method return types where
there is a clear need to represent "no result," and where using null
for that is overwhelmingly likely to cause errors.
A typical code smell is, instead of the code using method chaining to
handle an Optional returned from some method, it creates an Optional
from something that's nullable, in order to chain methods and avoid
conditionals.
I also suggest you to have a look at this answer to the question "Should Optional.ofNullable() be used for null check?", also by Stuart Marks.
With all that being said, combination Optional.of().orElseThrow() is both wrong and pointless:
If provided data is null method of() will raise an NPE and orElseThrow() will not be executed (i.e. its exception will get never be fired).
You're abusing the optional by creating an optional object not in order to return a nullable variable wrapped by it, but to hide the null-check (take a look at the quote above). That obscures the purpose of your code. You can use Objects.requireNonNull() instead to throw an exception if the given value must not be null or requireNonNullElse() to provide a default value.
For the same reason, you shouldn't use Optional.ofNullable().orElseThrow() at the first place.
Optional is like a Box
You might think of optional is if it is a parcel. When you need to send something, you go to the post office (i.e. returning from the method), where the thing that has to be sent is being placed into a box. When somebody (i.e. the caller) receives the parcel, it is being immediately unpacked. That is the whole lifecycle of the box called Optional.
When, according to the logic of your application, an object required to be returned from the method should not be null - use Optional.of(). It'll either send a parcel successfully or will emphasize that there's a problem by raising a NullPointerException.
If the given object is nullable by its nature, i.e. null isn't an abnormal case, then use Optional.ofNullable(), it'll fire either a box containing the object or an empty box.
And the caller (i.e. method that invokes the method returning an optional) is the one who has to unpack the box using a variety of tools that optional provides like orElseThrow(), orElseGet(), ifPresent(), etc.
I've been reading articles on beeing null safe in java, and how it's bad to return null, or of that sin, that is passing null as an argument. I get that it simplifies life, and people don't always read documentation, so they don't know wheather a method can return null, or if null can be passed to it. Annotations seem to just pollute the code, and there is no Kotlin-like null safety mechanism. In my current project I try to design everything in such a manner, that null is almost unnecessary, at least for the end-user.
I want to create a change listener (something like javafx.beans.value.ChangeListener), such that i can pass a previous and a current value to the changed() method. The thing is, I want it to be null safe, so I don't want to ever pass a null as an argument, even though it can change from no value to some value, or from some value to no value. I could add two additional methods for that situation and have something like:
public inteface ChangeListener<T> {
void valueSet(T current);
void valueChanged(T previous, T current);
void valueCleared(T previous);
}
This approach seems excessive though. I could also use
java.util.Optional<T> as arguments, but that adds additional boxing:
public inteface ChangeListener<T> {
void changed(Optional<T> previous, Optional<T> current);
}
Is there a more elegant option? Or should I force user to use some sort of a Null Object Pattern? Although that will create problems with the need to extend some classes. I could also stop caring, specify in the documentation what will happen if null is used, and let the user find the source of all the NullPointerExceptions.
Be a bit careful when people tell you "XYZ considered harmful". I've seen people do away with constructors altogether in favour of factory methods (such as Optional.of(...)), but as with everything, there's no single correct answer.
You seem to be struggling with trying to achieve several things (using simple code, having only one method in the listener, not using null values) that are mutually exclusive. So stop worrying and focus on what's important.
If your API users are idiots, and they don't read documentation, that's not really your problem. Null is not something dirty; it means "undefined". What is dubious is to use null if something unexpected happened, like "file not found", which should ideally be dealt with via an exception.
If "undefined" is a correct representation of an unset value in your API, then there's nothing wrong with using null.
After checking the JavaDocs for a method I was thinking of using, requiredNonNull, I stumbled across the first one with the single parameter (T obj).
However what is the actual purpose of this particular method with this signature? All it simply does is throw and NPE which I'm somewhat positive (as a I may be missing something obvious here) would be thrown anyway.
Throws:
NullPointerException - if obj is null
The latter actually makes sense in terms of debugging certain code, as the doc also states, it's primarily designed for parameter validation
public static <T> T requireNonNull(T obj,String message)
Checks that the specified object reference is not null and throws a customized NullPointerException if it is.
Therefore I can print specific information along with the NPE to make debugging a hell of a lot easier.
With this in mind I highly doubt I would come across a situation where I'd rather just use the former instead. Please do enlighten me.
tl;dr - Why would you ever use the overload which doesn't take a message.
A good principle when writing software is to catch errors as early as possible. The quicker you notice, for example, a bad value such as null being passed to a method, the easier it is to find out the cause and fix the problem.
If you pass null to a method that is not supposed to receive null, a NullPointerException will probably happen somewhere, as you already noticed. However, the exception might not happen until a few methods further down, and when it happens somewhere deep down, it will be more difficult to find the exact source of the error.
So, it's better when methods check their arguments up front and throw an exception as soon as they find an invalid value such as null.
edit - About the one-parameter version: even though you won't provide an error message, checking arguments and throwing an exception early will be more useful than letting the null pass down until an exception happens somewhere deeper down. The stack trace will point to the line where you used Objects.requireNonNull(...) and it should be obvious to you as a developer that that means you're not supposed to pass null. When you let a NullPointerException happen implicitly you don't know if the original programmer had the intent that the variable should not be null.
It is a utility method. Just a shortcut! (shortcut designers have their ways of doing their shortcut style).
Why throwing in the first place?
Security and Debugging.
Security: to not allow any illegal value in a sensitive place. (makes inner algorithm more sure about what are they doing and what are they having).
Debugging: for the program to die fast when something unexpected happens.
Some java method is null safe, but some are not. How to distinguish them?
I assume you mean in terms of the parameters? The documentation should state whether or not the arguments can be null, and when they can be null, what semantic meaning is inferred from nullity.
Unfortunately not all documentation is clear like this - and likewise it may not specify whether the return value might be null or not... in which case all you can do is experiment or look at the source code where possible :(
In general, I would suggest that you assume that you cannot pass null as a parameter unless the documentation clearly states that you can and what the corresponding behaviour is.
A problem with taking the default assumption that a parameter might be "null-safe" is that, even if that turns out to be true, it's not always clear without documentation what the corresponding behaviour actually is. "Not throwing an exception" doesn't actually indicate what alternative behaviour/default parameter/assumptions are then going to occur instead.
If you're designing an API, then where is's practical, I would suggest not actually encouraging null to be passed as a parameter to exposed methods/constructors, but rather have separate method signatures that include or not the various optional parameters. And in any case, you may then need to document in some way what actual behaviour is being taken to make up for the missing parameter.
If you're lucky, the parameter will be documented or annotated, or both. Unfortunately, most Java APIs lack both.
Some static analysis tools can use annotations to check whether you're passing a null value inappropriately. For example, the FindBugs tool includes support for these annotations:
#NonNull - The value must not be null
#CheckForNull - The value may contain null.
#Nullable - Whether the value may contain null or not depends on context.
Read the javadocs of the methods you are trying to call. If the javadocs don't specify this, then trial and error in a unit test is probably your best bet.
In a GWT solution. (so this is java code that is then compiled to javascript).
There are of course some classes.
Is it a good idea to make the setter check for Null on a String field?
something like this
public void setSomeField(String someField){
if (null != someField)
this.someField = someField;
else
this.someField = String.Empty;
}
Is this a good or bad idea? On the one had it will make coding easier as i wont have to check for null , on the other hand it would make me probably forget that I have to do this for other strings.
Thoughts?
Thanks
I say if such a logic is needed in your application, the setter is the place to put it. The main reason to have a get/set wrap around a private var is to be able to put logic around the access.
To answer the question of to default or not to default:
In my application it made sence to have a set of properties fall back to string.empty for display reasons. Although people could argue that the view should then cover these possibilities and check for nulls and display nothing, it was a lot of bloat all over my pages to do a check on every property.
That's why I started implementing SafeXX properties. So say I had 'myObj.Name' that could possibly have a null value, there would also be a property 'myObj.SafeName' that caught the null in the getter and returned a string.empty in stead. The little naming convention gives away that it is not the regular getter.
Here's something to consider. Would you expect this unit test to pass or fail?:
yourClass.setSomeField(null);
assertNull(yourClass.getSomeField());
If you're changing the null value to an empty string and returning that in getSomeField, then the client now has to check two conditions when testing...a String and a null String. Not a big deal, but what happens if you've got twenty String properties in the class...you'd probably better try to be consistent amongst all of the setters, and if you're not then the reason should probably be more obvious than just the documentation saying so.
There are certain conventions around getters and setters; certain expectations. If I call a setter on an object, then I usually expect the getter to return what I set. I don't expect it to return some representation of what I passed in that is more convenient for the class to work with internally. I don't care about the internals of the class, and don't want to.
If null really should be changed to "" for a valid reason (for example, it might mean "I don't care" and the default could be ""), go for it(but document it).
Otherwise, like if you just caught a NullPointerException and are trying to fix it this way, don't do it. If callers use obviously invalid values, the exception should be raised as soon as possible so that the caller notices the problem and fixes it before it bubbles up to a catastrophic, unexplainable error in a probably completely unrelated component.
In general, it is not a good idea to check for null values because the caller (the one who invokes the setter) may really want to set the value to null.
Suppose you query for 'someField' with this:
select * from ... where someField is null
If you set it as the empty string, the query above would fail.
If you don't want a field set to null, then don't set it to null.
This can be a good idea if you have no control over the code doing the setting, but if you do, it better to fix the problem at the source rather than put in work arounds like this.
That is hard to answer. On the first look it seems to make the usage better because you don't have to check for null all the time. But you loose the quality of null that means nothing is assigned. If you do String.Empty you already have ambiguity if someone gave you a String.Empty as parameter. Maybe it doesn't matter.
I personally (if at all) wouldn't do it in the setter. Inside your class null should have a value of its own. If you are for convenience a getter
return (this.someField != null) ? this.someField: String.Empty;
will do. You would keep the null internally to deal with but the outside has a more convenient method.
Generally and personally speaking I wouldn't do it. It looks good at first and makes a lot of things harder at later time.