4 Rules for using Java Optional

แชร์
ฝัง
  • เผยแพร่เมื่อ 1 ก.พ. 2025

ความคิดเห็น • 10

  • @viraj_shetty
    @viraj_shetty  ปีที่แล้ว

    Hi All - Use link below for my popular Java courses.
    Virtual Threads - www.mudraservices.com/udemycoupon.html?course=vthread
    Java Generics - www.mudraservices.com/udemycoupon.html?course=jgen
    For more of my courses, check out - www.mudraservices.com

  • @TheEntium
    @TheEntium ปีที่แล้ว +5

    Recently found your channel and I'm really impressed by the way you explain the concepts. I really appreciate your hard work!!

  • @anthonya880
    @anthonya880 11 หลายเดือนก่อน +1

    Hi Viraj,
    Is this part of any new upcoming course on Udemy ?

    • @viraj_shetty
      @viraj_shetty  11 หลายเดือนก่อน

      Not really. I am working on a small course on Java Generics and optionals may be a small part of it

  • @amajor5460
    @amajor5460 ปีที่แล้ว +1

    In your opinion, what's the advantage of doing
    if (optUser.isPresent()) { String firstName = optUser.get().firstName(); ...}
    as opposed to directly doing
    if (firstName != null) { ... }
    I think wrapping the object in an optional doesn't add any real advantage for this purpose. It's just doing the check slightly differently (isPresent() vs != null)

    • @viraj_shetty
      @viraj_shetty  ปีที่แล้ว

      A returned Optional type signals to the caller that a null is possible and the caller needs to handle it. In a way - the caller is forced to think about it. Without it, a developer can easily forget to do the null check. You can see Optionals now being used in the Java APIs themselves.

    • @amajor5460
      @amajor5460 ปีที่แล้ว +1

      it's also possible for a developer to do optional.get() without checking for ifPresent() then they could potentially run into a null pointer exception. but i get your point..

    • @viraj_shetty
      @viraj_shetty  ปีที่แล้ว +1

      You bring up good points. Overuse of Optionals is also not a good thing. One advantage of Java Optional is that it works well with functional/fluent APIs - where we chain a bunch of methods. Whereas a returned "null" would have ended this chain, an Optional would allow it to proceed. I am creating another video on using Fluent APIs with Optional. It's no accident that Optional return types are heavily used in Java Streams where functional/fluent methods are used.

    • @amajor5460
      @amajor5460 ปีที่แล้ว

      Yea, I think that's a good use case