Optional isPresent vs orElse(null)

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
10
down vote

favorite
1












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.







share|improve this question


















  • 4




    By the way, the java.util.Date class was supplanted years ago by java.time.Instant.
    – Basil Bourque
    Aug 28 at 4:19






  • 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 at 6:50














up vote
10
down vote

favorite
1












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.







share|improve this question


















  • 4




    By the way, the java.util.Date class was supplanted years ago by java.time.Instant.
    – Basil Bourque
    Aug 28 at 4:19






  • 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 at 6:50












up vote
10
down vote

favorite
1









up vote
10
down vote

favorite
1






1





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.







share|improve this question














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.









share|improve this question













share|improve this question




share|improve this question








edited Aug 30 at 6:58

























asked Aug 27 at 21:55









Sadiq Ali

5871515




5871515







  • 4




    By the way, the java.util.Date class was supplanted years ago by java.time.Instant.
    – Basil Bourque
    Aug 28 at 4:19






  • 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 at 6:50












  • 4




    By the way, the java.util.Date class was supplanted years ago by java.time.Instant.
    – Basil Bourque
    Aug 28 at 4:19






  • 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 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 at 4:19




By the way, the java.util.Date class was supplanted years ago by java.time.Instant.
– Basil Bourque
Aug 28 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 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 at 6:50












4 Answers
4






active

oldest

votes

















up vote
16
down vote



accepted










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.






share|improve this answer


















  • 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 at 22:05






  • 3




    is get() dangerous if you call it after checking the presence? am I missing something?
    – Sadiq Ali
    Aug 27 at 22:08







  • 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 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 at 22:18






  • 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 at 10:20

















up vote
4
down vote













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.






share|improve this answer
















  • 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 at 4:10


















up vote
2
down vote













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.






share|improve this answer





























    up vote
    0
    down vote













    you can also do:



    Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep -> 
    ep.setDateModified(new Date());
    return expectedPackageRepository.saveAndFlush(ep);
    );





    share|improve this answer




















    • @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 at 11:42










    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',
    convertImagesToLinks: true,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    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






























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    16
    down vote



    accepted










    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.






    share|improve this answer


















    • 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 at 22:05






    • 3




      is get() dangerous if you call it after checking the presence? am I missing something?
      – Sadiq Ali
      Aug 27 at 22:08







    • 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 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 at 22:18






    • 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 at 10:20














    up vote
    16
    down vote



    accepted










    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.






    share|improve this answer


















    • 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 at 22:05






    • 3




      is get() dangerous if you call it after checking the presence? am I missing something?
      – Sadiq Ali
      Aug 27 at 22:08







    • 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 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 at 22:18






    • 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 at 10:20












    up vote
    16
    down vote



    accepted







    up vote
    16
    down vote



    accepted






    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.






    share|improve this answer














    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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Aug 27 at 22:10

























    answered Aug 27 at 22:00









    Poger

    659813




    659813







    • 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 at 22:05






    • 3




      is get() dangerous if you call it after checking the presence? am I missing something?
      – Sadiq Ali
      Aug 27 at 22:08







    • 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 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 at 22:18






    • 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 at 10:20












    • 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 at 22:05






    • 3




      is get() dangerous if you call it after checking the presence? am I missing something?
      – Sadiq Ali
      Aug 27 at 22:08







    • 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 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 at 22:18






    • 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 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 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 at 22:05




    3




    3




    is get() dangerous if you call it after checking the presence? am I missing something?
    – Sadiq Ali
    Aug 27 at 22:08





    is get() dangerous if you call it after checking the presence? am I missing something?
    – Sadiq Ali
    Aug 27 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 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 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 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 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 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 at 10:20












    up vote
    4
    down vote













    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.






    share|improve this answer
















    • 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 at 4:10















    up vote
    4
    down vote













    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.






    share|improve this answer
















    • 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 at 4:10













    up vote
    4
    down vote










    up vote
    4
    down vote









    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.






    share|improve this answer












    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.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Aug 28 at 3:01









    Eugene

    58.9k979138




    58.9k979138







    • 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 at 4:10













    • 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 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 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 at 4:10











    up vote
    2
    down vote













    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.






    share|improve this answer


























      up vote
      2
      down vote













      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.






      share|improve this answer
























        up vote
        2
        down vote










        up vote
        2
        down vote









        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.






        share|improve this answer














        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Sep 1 at 5:42

























        answered Aug 28 at 4:04









        Basil Bourque

        94.6k23326478




        94.6k23326478




















            up vote
            0
            down vote













            you can also do:



            Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep -> 
            ep.setDateModified(new Date());
            return expectedPackageRepository.saveAndFlush(ep);
            );





            share|improve this answer




















            • @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 at 11:42














            up vote
            0
            down vote













            you can also do:



            Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep -> 
            ep.setDateModified(new Date());
            return expectedPackageRepository.saveAndFlush(ep);
            );





            share|improve this answer




















            • @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 at 11:42












            up vote
            0
            down vote










            up vote
            0
            down vote









            you can also do:



            Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep -> 
            ep.setDateModified(new Date());
            return expectedPackageRepository.saveAndFlush(ep);
            );





            share|improve this answer












            you can also do:



            Optional<ExpectedPackage> updatedPackage = expectedPackageRepository.findById(1).map(ep -> 
            ep.setDateModified(new Date());
            return expectedPackageRepository.saveAndFlush(ep);
            );






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 28 at 3:11









            Ritesh

            5,60222739




            5,60222739











            • @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 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 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 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 at 11:42

















             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            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













































































            Comments

            Popular posts from this blog

            What does second last employer means? [closed]

            List of Gilmore Girls characters

            Confectionery