Reputation: 451
The orignal code is
if(object==null){
throw new CustomException(ErrorEnum.OBJECT_NULL)
}
now I want to use Optional
to handle NullPointerException
.
Just like this
Optional.ofNullable(object).orElseThrow(()->{throw new CustomException(ErrorEnum.OBJECT_NULL);}
But doing this makes code much longer than original. Maybe I should use the first way to solve the problem?
Upvotes: 18
Views: 36467
Reputation: 132370
I agree with commenters and other answers who are saying that Optional
is unnecessary here. Indeed, it echoes advice I've also given elsewhere. In this case if one already has a nullable variable object
then it's rather roundabout to wrap it in an Optional
just to throw an exception, and as you observe, it's longer than the original.
The question to ask instead is, where did the reference in object
come from? Did it come from another method that returns a nullable reference? If so, then perhaps that other method should be refactored to return Optional<T>
instead of a nullable reference of type T
.
Upvotes: 7
Reputation: 56423
Optionals are intended as a safer alternative than a reference of type T
that refers to an object or null
, but it's only safer or better if you use it correctly. Both the examples given are safe but it's not better to use an Optional to solely replace an if
statement as shown.
Also, note that you're expected to supply the desired exception, not to throw it. i.e.
orElseThrow(() ->{throw new CustomException(ErrorEnum.OBJECT_NULL);}
should be
orElseThrow(() ->{return new CustomException(ErrorEnum.OBJECT_NULL);}
or better
orElseThrow(() -> new CustomException(ErrorEnum.OBJECT_NULL));
That said, in this particular, I'd go with the first approach. optionals are useful when they're used correctly, i.e as a method return type to wrap a value that may or may not be present as well as code documentation. Thus, in this case, there is no need to use it.
Upvotes: 10
Reputation: 3737
Optional.ofNullable(object).orElseThrow(() -> new CustomException(ErrorEnum.OBJECT_NULL));
If you read the method definition in Optional javadoc
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable
This shows that you require a Supplier of X where X extends Throwable.
Supplier is an interface with a method get
. Since it has only 1 abstract method, its a Functional Interface which you can instantiate using Lambda expressions.
Since it takes no parameter we will do () -> new CustomException("your error message");
This creates an instance of Supplier
which returns a CustomException object when get
is invoked which I am passing as the parameter to the orElseThrow
.
Having said all that, you should not use Optional for this use case as it provides no benefit to you.
Hope that helps :)
Upvotes: 24