Optional isPresent vs orElse(null)
I was updating the dependencies to Spring 5 in my project and was bombarded with compilation errors where the method definition of findOne()
has been replaced by findById()
which now returns an Optional
(correct me if I am wrong).
While refactoring, I came across multiple approaches that I can choose to adopt, and I would therefore like some input on which one is to be preferred.
1st approach:
ExpectedPackage ep = expectedPackageRepository.findById(1).orElse(null);
if(ep != null)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
2nd approach:
Optional<ExpectedPackage> ep = expectedPackageRepository.findById(1);
if(ep.isPresent())
ep.get().setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep.get());
Or is there a third and better approach that I have missed? I went through several questions and a couple of articles, but I did not find a clear answer.
java java-8 spring-data-jpa
add a comment |
I was updating the dependencies to Spring 5 in my project and was bombarded with compilation errors where the method definition of findOne()
has been replaced by findById()
which now returns an Optional
(correct me if I am wrong).
While refactoring, I came across multiple approaches that I can choose to adopt, and I would therefore like some input on which one is to be preferred.
1st approach:
ExpectedPackage ep = expectedPackageRepository.findById(1).orElse(null);
if(ep != null)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
2nd approach:
Optional<ExpectedPackage> ep = expectedPackageRepository.findById(1);
if(ep.isPresent())
ep.get().setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep.get());
Or is there a third and better approach that I have missed? I went through several questions and a couple of articles, but I did not find a clear answer.
java java-8 spring-data-jpa
4
By the way, thejava.util.Date
class was supplanted years ago byjava.time.Instant
.
– Basil Bourque
Aug 28 '18 at 4:19
1
Neither. The whole purpose ofOptional
is to avoidnull
; the first does not do this and the second is bascially justnull
by another name.
– Boris the Spider
Aug 28 '18 at 6:50
add a comment |
I was updating the dependencies to Spring 5 in my project and was bombarded with compilation errors where the method definition of findOne()
has been replaced by findById()
which now returns an Optional
(correct me if I am wrong).
While refactoring, I came across multiple approaches that I can choose to adopt, and I would therefore like some input on which one is to be preferred.
1st approach:
ExpectedPackage ep = expectedPackageRepository.findById(1).orElse(null);
if(ep != null)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
2nd approach:
Optional<ExpectedPackage> ep = expectedPackageRepository.findById(1);
if(ep.isPresent())
ep.get().setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep.get());
Or is there a third and better approach that I have missed? I went through several questions and a couple of articles, but I did not find a clear answer.
java java-8 spring-data-jpa
I was updating the dependencies to Spring 5 in my project and was bombarded with compilation errors where the method definition of findOne()
has been replaced by findById()
which now returns an Optional
(correct me if I am wrong).
While refactoring, I came across multiple approaches that I can choose to adopt, and I would therefore like some input on which one is to be preferred.
1st approach:
ExpectedPackage ep = expectedPackageRepository.findById(1).orElse(null);
if(ep != null)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
2nd approach:
Optional<ExpectedPackage> ep = expectedPackageRepository.findById(1);
if(ep.isPresent())
ep.get().setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep.get());
Or is there a third and better approach that I have missed? I went through several questions and a couple of articles, but I did not find a clear answer.
java java-8 spring-data-jpa
java java-8 spring-data-jpa
edited Aug 30 '18 at 6:58
Sadiq Ali
asked Aug 27 '18 at 21:55
Sadiq AliSadiq Ali
7121617
7121617
4
By the way, thejava.util.Date
class was supplanted years ago byjava.time.Instant
.
– Basil Bourque
Aug 28 '18 at 4:19
1
Neither. The whole purpose ofOptional
is to avoidnull
; the first does not do this and the second is bascially justnull
by another name.
– Boris the Spider
Aug 28 '18 at 6:50
add a comment |
4
By the way, thejava.util.Date
class was supplanted years ago byjava.time.Instant
.
– Basil Bourque
Aug 28 '18 at 4:19
1
Neither. The whole purpose ofOptional
is to avoidnull
; the first does not do this and the second is bascially justnull
by another name.
– Boris the Spider
Aug 28 '18 at 6:50
4
4
By the way, the
java.util.Date
class was supplanted years ago by java.time.Instant
.– Basil Bourque
Aug 28 '18 at 4:19
By the way, the
java.util.Date
class was supplanted years ago by java.time.Instant
.– Basil Bourque
Aug 28 '18 at 4:19
1
1
Neither. The whole purpose of
Optional
is to avoid null
; the first does not do this and the second is bascially just null
by another name.– Boris the Spider
Aug 28 '18 at 6:50
Neither. The whole purpose of
Optional
is to avoid null
; the first does not do this and the second is bascially just null
by another name.– Boris the Spider
Aug 28 '18 at 6:50
add a comment |
4 Answers
4
active
oldest
votes
You can also do:
expectedPackageRepository.findById(1).ifPresent(
ep ->
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
);
Ideally, you would also extract the part between brackets () to a separate method. Then, you could write like this:
expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);
Where:
void doSomethingWithEp(ExpectedPackage ep)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
You can read the documentation of ifPresent
here: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ifPresent-java.util.function.Consumer-
As it states, it will perform the specified action if the value is present and do nothing otherwise.
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 '18 at 22:05
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 '18 at 22:08
1
If you callget()
immediately after a check toisPresent()
then you should be fine. The method I presented just seems more clean in your case.
– Poger
Aug 27 '18 at 22:14
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 '18 at 22:18
2
The rule of thumb is: avoidisPresent
andget
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).
– Ole V.V.
Aug 28 '18 at 10:20
|
show 3 more comments
The other answer is basically some refactoring of your second approach, which has nothing wrong per-se, it's just a matter of style. Of course chaining and extraction to a separate method will make this a lot more readable and clear, no doubt (+1 from me), especially since the correct usage of ifPresent
.
I'd just add here that get
, well, was seen as somehow a design error ( or may be a bad method name, probably that came from guava
mindset ). Using get
even if it documented to throw an Exception when that value is missing is somehow weird ( if you think getters here, you would not expect a getter
to throw an Exception). And you would not expect that get
needs to be called after isPresent
, at least not on the very first interactions with Optional
. Thus get
was proposed to be deprecated ( and hopefully removed ), thus java-10 adds a better addition orElseThrow()
- this makes sense right after you read it, cause the throwing part is in the name of the method, so no surprises.
Also, someone should tell you about that usage of new Date()
that when used with Optional
from java-8 just looks weird, there are much better time/date related classes already.
I am also not very sure why you are updating a modified date manually, when there are spring annotations for that like PreUpdate/PrePersist
.
3
Brian Goetz has acknowledged that naming theOptional::get
method was a mistake. Should have been namedOptional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png
– Basil Bourque
Aug 28 '18 at 4:10
add a comment |
Yes, there are other approaches.
If you absolutely expect there always to be a value, then use Optional::orElseThrow
to throw an Exception if a null appears.
If you expect a null to possibly arrive, and have an alternative instance available as a fall-back option, use Optional::orElse
.
If the fall-back instance is not on hand, but you have a function to call to provide a fall-back instance, use Optional::orElseGet
.
If you don’t care about receiving a null, and want to do nothing when a null arrives, use Optional::ifPresent
. Pass the block of code to be run if a value arrives.
If you only care if a value arrives that meets some requirement, use Optional::filter
. Pass a Predicate
defining your requirement. For example, we care only if an Optional< String >
contains text and that text has the word purple
in it: myOptional.filter( s -> s.contains( "purple" ) ).ifPresent( this::print ) ;
. If null received, our desired operation (a call to print
in this example) never happens. If a value was received but failed to meet our predicate, our desired operation never happens.
Doing if( myOptional.isPresent() ) SomeClass x = myOptional.get() ; …
is valid, and safe. But this is not the original intent of Optional
as it is basically the same as doing an old-fashioned null-check if ( null == x ) …
. The other methods on Optional
provide a more clear and elegant way to express your intentions towards a possible null arriving.
add a comment |
you can also do:
Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep ->
ep.setDateModified(new Date());
return expectedPackageRepository.saveAndFlush(ep);
);
@BorisfindById
returnsOptional
andmap
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
– Ritesh
Aug 28 '18 at 11:42
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52047479%2foptional-ispresent-vs-orelsenull%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can also do:
expectedPackageRepository.findById(1).ifPresent(
ep ->
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
);
Ideally, you would also extract the part between brackets () to a separate method. Then, you could write like this:
expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);
Where:
void doSomethingWithEp(ExpectedPackage ep)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
You can read the documentation of ifPresent
here: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ifPresent-java.util.function.Consumer-
As it states, it will perform the specified action if the value is present and do nothing otherwise.
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 '18 at 22:05
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 '18 at 22:08
1
If you callget()
immediately after a check toisPresent()
then you should be fine. The method I presented just seems more clean in your case.
– Poger
Aug 27 '18 at 22:14
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 '18 at 22:18
2
The rule of thumb is: avoidisPresent
andget
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).
– Ole V.V.
Aug 28 '18 at 10:20
|
show 3 more comments
You can also do:
expectedPackageRepository.findById(1).ifPresent(
ep ->
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
);
Ideally, you would also extract the part between brackets () to a separate method. Then, you could write like this:
expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);
Where:
void doSomethingWithEp(ExpectedPackage ep)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
You can read the documentation of ifPresent
here: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ifPresent-java.util.function.Consumer-
As it states, it will perform the specified action if the value is present and do nothing otherwise.
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 '18 at 22:05
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 '18 at 22:08
1
If you callget()
immediately after a check toisPresent()
then you should be fine. The method I presented just seems more clean in your case.
– Poger
Aug 27 '18 at 22:14
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 '18 at 22:18
2
The rule of thumb is: avoidisPresent
andget
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).
– Ole V.V.
Aug 28 '18 at 10:20
|
show 3 more comments
You can also do:
expectedPackageRepository.findById(1).ifPresent(
ep ->
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
);
Ideally, you would also extract the part between brackets () to a separate method. Then, you could write like this:
expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);
Where:
void doSomethingWithEp(ExpectedPackage ep)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
You can read the documentation of ifPresent
here: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ifPresent-java.util.function.Consumer-
As it states, it will perform the specified action if the value is present and do nothing otherwise.
You can also do:
expectedPackageRepository.findById(1).ifPresent(
ep ->
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
);
Ideally, you would also extract the part between brackets () to a separate method. Then, you could write like this:
expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);
Where:
void doSomethingWithEp(ExpectedPackage ep)
ep.setDateModified(new Date());
expectedPackageRepository.saveAndFlush(ep);
You can read the documentation of ifPresent
here: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ifPresent-java.util.function.Consumer-
As it states, it will perform the specified action if the value is present and do nothing otherwise.
edited Aug 27 '18 at 22:10
answered Aug 27 '18 at 22:00
PogerPoger
8281015
8281015
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 '18 at 22:05
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 '18 at 22:08
1
If you callget()
immediately after a check toisPresent()
then you should be fine. The method I presented just seems more clean in your case.
– Poger
Aug 27 '18 at 22:14
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 '18 at 22:18
2
The rule of thumb is: avoidisPresent
andget
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).
– Ole V.V.
Aug 28 '18 at 10:20
|
show 3 more comments
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 '18 at 22:05
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 '18 at 22:08
1
If you callget()
immediately after a check toisPresent()
then you should be fine. The method I presented just seems more clean in your case.
– Poger
Aug 27 '18 at 22:14
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 '18 at 22:18
2
The rule of thumb is: avoidisPresent
andget
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).
– Ole V.V.
Aug 28 '18 at 10:20
2
2
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 '18 at 22:05
As Poger said. The great thig about ifPresent is you don't have to call the "dangerous" get method, instead teh value is presented to you.
– tpdi
Aug 27 '18 at 22:05
3
3
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 '18 at 22:08
is get() dangerous if you call it after checking the presence? am I missing something?
– Sadiq Ali
Aug 27 '18 at 22:08
1
1
If you call
get()
immediately after a check to isPresent()
then you should be fine. The method I presented just seems more clean in your case.– Poger
Aug 27 '18 at 22:14
If you call
get()
immediately after a check to isPresent()
then you should be fine. The method I presented just seems more clean in your case.– Poger
Aug 27 '18 at 22:14
2
2
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 '18 at 22:18
And if you apply correct transaction/session boundaries (with the @Transactional annotation, for example), then you don’t need to call the save method on the repository, making the code even simpler
– Erwin Bolwidt
Aug 27 '18 at 22:18
2
2
The rule of thumb is: avoid
isPresent
and get
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).– Ole V.V.
Aug 28 '18 at 10:20
The rule of thumb is: avoid
isPresent
and get
. This answer demonstrates that there are clearer alternatives, and that is most often the case (though not always).– Ole V.V.
Aug 28 '18 at 10:20
|
show 3 more comments
The other answer is basically some refactoring of your second approach, which has nothing wrong per-se, it's just a matter of style. Of course chaining and extraction to a separate method will make this a lot more readable and clear, no doubt (+1 from me), especially since the correct usage of ifPresent
.
I'd just add here that get
, well, was seen as somehow a design error ( or may be a bad method name, probably that came from guava
mindset ). Using get
even if it documented to throw an Exception when that value is missing is somehow weird ( if you think getters here, you would not expect a getter
to throw an Exception). And you would not expect that get
needs to be called after isPresent
, at least not on the very first interactions with Optional
. Thus get
was proposed to be deprecated ( and hopefully removed ), thus java-10 adds a better addition orElseThrow()
- this makes sense right after you read it, cause the throwing part is in the name of the method, so no surprises.
Also, someone should tell you about that usage of new Date()
that when used with Optional
from java-8 just looks weird, there are much better time/date related classes already.
I am also not very sure why you are updating a modified date manually, when there are spring annotations for that like PreUpdate/PrePersist
.
3
Brian Goetz has acknowledged that naming theOptional::get
method was a mistake. Should have been namedOptional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png
– Basil Bourque
Aug 28 '18 at 4:10
add a comment |
The other answer is basically some refactoring of your second approach, which has nothing wrong per-se, it's just a matter of style. Of course chaining and extraction to a separate method will make this a lot more readable and clear, no doubt (+1 from me), especially since the correct usage of ifPresent
.
I'd just add here that get
, well, was seen as somehow a design error ( or may be a bad method name, probably that came from guava
mindset ). Using get
even if it documented to throw an Exception when that value is missing is somehow weird ( if you think getters here, you would not expect a getter
to throw an Exception). And you would not expect that get
needs to be called after isPresent
, at least not on the very first interactions with Optional
. Thus get
was proposed to be deprecated ( and hopefully removed ), thus java-10 adds a better addition orElseThrow()
- this makes sense right after you read it, cause the throwing part is in the name of the method, so no surprises.
Also, someone should tell you about that usage of new Date()
that when used with Optional
from java-8 just looks weird, there are much better time/date related classes already.
I am also not very sure why you are updating a modified date manually, when there are spring annotations for that like PreUpdate/PrePersist
.
3
Brian Goetz has acknowledged that naming theOptional::get
method was a mistake. Should have been namedOptional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png
– Basil Bourque
Aug 28 '18 at 4:10
add a comment |
The other answer is basically some refactoring of your second approach, which has nothing wrong per-se, it's just a matter of style. Of course chaining and extraction to a separate method will make this a lot more readable and clear, no doubt (+1 from me), especially since the correct usage of ifPresent
.
I'd just add here that get
, well, was seen as somehow a design error ( or may be a bad method name, probably that came from guava
mindset ). Using get
even if it documented to throw an Exception when that value is missing is somehow weird ( if you think getters here, you would not expect a getter
to throw an Exception). And you would not expect that get
needs to be called after isPresent
, at least not on the very first interactions with Optional
. Thus get
was proposed to be deprecated ( and hopefully removed ), thus java-10 adds a better addition orElseThrow()
- this makes sense right after you read it, cause the throwing part is in the name of the method, so no surprises.
Also, someone should tell you about that usage of new Date()
that when used with Optional
from java-8 just looks weird, there are much better time/date related classes already.
I am also not very sure why you are updating a modified date manually, when there are spring annotations for that like PreUpdate/PrePersist
.
The other answer is basically some refactoring of your second approach, which has nothing wrong per-se, it's just a matter of style. Of course chaining and extraction to a separate method will make this a lot more readable and clear, no doubt (+1 from me), especially since the correct usage of ifPresent
.
I'd just add here that get
, well, was seen as somehow a design error ( or may be a bad method name, probably that came from guava
mindset ). Using get
even if it documented to throw an Exception when that value is missing is somehow weird ( if you think getters here, you would not expect a getter
to throw an Exception). And you would not expect that get
needs to be called after isPresent
, at least not on the very first interactions with Optional
. Thus get
was proposed to be deprecated ( and hopefully removed ), thus java-10 adds a better addition orElseThrow()
- this makes sense right after you read it, cause the throwing part is in the name of the method, so no surprises.
Also, someone should tell you about that usage of new Date()
that when used with Optional
from java-8 just looks weird, there are much better time/date related classes already.
I am also not very sure why you are updating a modified date manually, when there are spring annotations for that like PreUpdate/PrePersist
.
answered Aug 28 '18 at 3:01
EugeneEugene
71.3k9102170
71.3k9102170
3
Brian Goetz has acknowledged that naming theOptional::get
method was a mistake. Should have been namedOptional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png
– Basil Bourque
Aug 28 '18 at 4:10
add a comment |
3
Brian Goetz has acknowledged that naming theOptional::get
method was a mistake. Should have been namedOptional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png
– Basil Bourque
Aug 28 '18 at 4:10
3
3
Brian Goetz has acknowledged that naming the
Optional::get
method was a mistake. Should have been named Optional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png– Basil Bourque
Aug 28 '18 at 4:10
Brian Goetz has acknowledged that naming the
Optional::get
method was a mistake. Should have been named Optional::getOrThrowSomeHorribleIfTheThingIsEmpty
. i.stack.imgur.com/LPg1Z.png– Basil Bourque
Aug 28 '18 at 4:10
add a comment |
Yes, there are other approaches.
If you absolutely expect there always to be a value, then use Optional::orElseThrow
to throw an Exception if a null appears.
If you expect a null to possibly arrive, and have an alternative instance available as a fall-back option, use Optional::orElse
.
If the fall-back instance is not on hand, but you have a function to call to provide a fall-back instance, use Optional::orElseGet
.
If you don’t care about receiving a null, and want to do nothing when a null arrives, use Optional::ifPresent
. Pass the block of code to be run if a value arrives.
If you only care if a value arrives that meets some requirement, use Optional::filter
. Pass a Predicate
defining your requirement. For example, we care only if an Optional< String >
contains text and that text has the word purple
in it: myOptional.filter( s -> s.contains( "purple" ) ).ifPresent( this::print ) ;
. If null received, our desired operation (a call to print
in this example) never happens. If a value was received but failed to meet our predicate, our desired operation never happens.
Doing if( myOptional.isPresent() ) SomeClass x = myOptional.get() ; …
is valid, and safe. But this is not the original intent of Optional
as it is basically the same as doing an old-fashioned null-check if ( null == x ) …
. The other methods on Optional
provide a more clear and elegant way to express your intentions towards a possible null arriving.
add a comment |
Yes, there are other approaches.
If you absolutely expect there always to be a value, then use Optional::orElseThrow
to throw an Exception if a null appears.
If you expect a null to possibly arrive, and have an alternative instance available as a fall-back option, use Optional::orElse
.
If the fall-back instance is not on hand, but you have a function to call to provide a fall-back instance, use Optional::orElseGet
.
If you don’t care about receiving a null, and want to do nothing when a null arrives, use Optional::ifPresent
. Pass the block of code to be run if a value arrives.
If you only care if a value arrives that meets some requirement, use Optional::filter
. Pass a Predicate
defining your requirement. For example, we care only if an Optional< String >
contains text and that text has the word purple
in it: myOptional.filter( s -> s.contains( "purple" ) ).ifPresent( this::print ) ;
. If null received, our desired operation (a call to print
in this example) never happens. If a value was received but failed to meet our predicate, our desired operation never happens.
Doing if( myOptional.isPresent() ) SomeClass x = myOptional.get() ; …
is valid, and safe. But this is not the original intent of Optional
as it is basically the same as doing an old-fashioned null-check if ( null == x ) …
. The other methods on Optional
provide a more clear and elegant way to express your intentions towards a possible null arriving.
add a comment |
Yes, there are other approaches.
If you absolutely expect there always to be a value, then use Optional::orElseThrow
to throw an Exception if a null appears.
If you expect a null to possibly arrive, and have an alternative instance available as a fall-back option, use Optional::orElse
.
If the fall-back instance is not on hand, but you have a function to call to provide a fall-back instance, use Optional::orElseGet
.
If you don’t care about receiving a null, and want to do nothing when a null arrives, use Optional::ifPresent
. Pass the block of code to be run if a value arrives.
If you only care if a value arrives that meets some requirement, use Optional::filter
. Pass a Predicate
defining your requirement. For example, we care only if an Optional< String >
contains text and that text has the word purple
in it: myOptional.filter( s -> s.contains( "purple" ) ).ifPresent( this::print ) ;
. If null received, our desired operation (a call to print
in this example) never happens. If a value was received but failed to meet our predicate, our desired operation never happens.
Doing if( myOptional.isPresent() ) SomeClass x = myOptional.get() ; …
is valid, and safe. But this is not the original intent of Optional
as it is basically the same as doing an old-fashioned null-check if ( null == x ) …
. The other methods on Optional
provide a more clear and elegant way to express your intentions towards a possible null arriving.
Yes, there are other approaches.
If you absolutely expect there always to be a value, then use Optional::orElseThrow
to throw an Exception if a null appears.
If you expect a null to possibly arrive, and have an alternative instance available as a fall-back option, use Optional::orElse
.
If the fall-back instance is not on hand, but you have a function to call to provide a fall-back instance, use Optional::orElseGet
.
If you don’t care about receiving a null, and want to do nothing when a null arrives, use Optional::ifPresent
. Pass the block of code to be run if a value arrives.
If you only care if a value arrives that meets some requirement, use Optional::filter
. Pass a Predicate
defining your requirement. For example, we care only if an Optional< String >
contains text and that text has the word purple
in it: myOptional.filter( s -> s.contains( "purple" ) ).ifPresent( this::print ) ;
. If null received, our desired operation (a call to print
in this example) never happens. If a value was received but failed to meet our predicate, our desired operation never happens.
Doing if( myOptional.isPresent() ) SomeClass x = myOptional.get() ; …
is valid, and safe. But this is not the original intent of Optional
as it is basically the same as doing an old-fashioned null-check if ( null == x ) …
. The other methods on Optional
provide a more clear and elegant way to express your intentions towards a possible null arriving.
edited Sep 1 '18 at 5:42
answered Aug 28 '18 at 4:04
Basil BourqueBasil Bourque
115k29393555
115k29393555
add a comment |
add a comment |
you can also do:
Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep ->
ep.setDateModified(new Date());
return expectedPackageRepository.saveAndFlush(ep);
);
@BorisfindById
returnsOptional
andmap
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
– Ritesh
Aug 28 '18 at 11:42
add a comment |
you can also do:
Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep ->
ep.setDateModified(new Date());
return expectedPackageRepository.saveAndFlush(ep);
);
@BorisfindById
returnsOptional
andmap
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
– Ritesh
Aug 28 '18 at 11:42
add a comment |
you can also do:
Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep ->
ep.setDateModified(new Date());
return expectedPackageRepository.saveAndFlush(ep);
);
you can also do:
Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep ->
ep.setDateModified(new Date());
return expectedPackageRepository.saveAndFlush(ep);
);
answered Aug 28 '18 at 3:11
RiteshRitesh
6,06023140
6,06023140
@BorisfindById
returnsOptional
andmap
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
– Ritesh
Aug 28 '18 at 11:42
add a comment |
@BorisfindById
returnsOptional
andmap
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
– Ritesh
Aug 28 '18 at 11:42
@Boris
findById
returns Optional
and map
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.– Ritesh
Aug 28 '18 at 11:42
@Boris
findById
returns Optional
and map
is the termination method. Please see the map method of Optional: If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.– Ritesh
Aug 28 '18 at 11:42
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52047479%2foptional-ispresent-vs-orelsenull%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
4
By the way, the
java.util.Date
class was supplanted years ago byjava.time.Instant
.– Basil Bourque
Aug 28 '18 at 4:19
1
Neither. The whole purpose of
Optional
is to avoidnull
; the first does not do this and the second is bascially justnull
by another name.– Boris the Spider
Aug 28 '18 at 6:50