Is it good idea to use Optional.of() method to make method chaining?

前端 未结 3 1955
误落风尘
误落风尘 2021-01-07 04:07

Is it good idea to use Optional.of() method to make method chaining ?

i had a conversation with group of collegues about Optional.of() method. currently one of the

相关标签:
3条回答
  • 2021-01-07 04:26

    I think, Java Optional is made for these type of use cases only - To avoid null checks and do operations via chaining & without the fear of NPE.

    I don't think you are overusing Optional.

    From the Official Article from Oracle

    The purpose of Optional is not to replace every single null reference in your codebase but rather to help design better APIs in which—just by reading the signature of a method—users can tell whether to expect an optional value. In addition, Optional forces you to actively unwrap an Optional to deal with the absence of a value; as a result, you protect your code against unintended null pointer exceptions.

    0 讨论(0)
  • 2021-01-07 04:30

    If initTxDataResponse is nullable, then maybe it should be like this ?

    Optional<TxResponse> initTxDataResponse = 
            gateway.initiateTx(initTxDataRequest);
    
    response.map(....)
    
    0 讨论(0)
  • 2021-01-07 04:33

    If you don’t mind an answer without code, just my 0.02$.

    We have been fighting over this at my work place (in code reviews) quite a lot. To be frank I am sometimes lost as to when it is correct (read intended by the creators of it) or not. I don’t even think that at the time of creation, Stuart Marks and the others were sure how this would be (ab)used. Like any other feature in the Java language, it will get abused, be sure of that. But over time, best practices will appear and people will use that.

    I tend to be on the side that iff it does not hurt performance, your usage is OK. At least its sooo easy to read (speaking for myself here), compared to if else checks; but again it might be me doing (too) much Java-8 and above code.

    That being said, it’s way too easy to turn it into a total mess, where that bound is, is up to you (and most probably your team).

    0 讨论(0)
提交回复
热议问题