Optionals Bad And Good Practice

Поділитися
Вставка
  • Опубліковано 4 лют 2024
  • Enjoy! :-)
    Thank you for commenting and asking questions.
    Discord server - Where we discuss programming languages and tech - Please use the right channel to your input / question :)
    / discord
    My web site:
    www.codeinvestigator.com
    One.com - Easy web sites
    one.me/daauttew
    The code is located here:
    github.com/ekim197711
    Follow me on twitter:
    / mikemoelnielsen
    Chat on Discord:
    / discord
    Support me on Patreon:
    / mikemoellernielsen
    Background nature video:
    Video by Engin Akyurt from Pexels
    www.pexels.com/video/beauty-o...
  • Наука та технологія

КОМЕНТАРІ • 6

  • @lost.empathy
    @lost.empathy 3 місяці тому +1

    Thank you. I was wondering why in some parts of our legacy projects we have Optional of List in JPA Repositories. It was so because sometimes people got null if they wrote @Query with unused method parameter. But as I read in docs repository methods guarantee to return collections or whatever was set as return wrapper type. What do you think, should I do null checks when I get data from repository methods or NPE itself will point to bad quality code?

    • @MikesTechCorner
      @MikesTechCorner  3 місяці тому +2

      This is a very good example. The Reposities can return Optional but should never return Optional. And making mistakes with query parameters is a common mistake. :)

  • @ilyastuit
    @ilyastuit 3 місяці тому +1

    Nice video!
    I’m wondering why is it bad practice to “use Optional with Lists/Collections”.
    Let’s consider the case when I have reference to List, but I don’t know whether it is null or empty, and I want to perform some actions declaratively / in a functional manner.
    With Optional:
    List otherElements = Optional.ofNullable(potentiallyNullOrEmptyList)
    .filter(elements -> !elements.isEmpty())
    .map(elements -> repository.findAllByXXAndWhereElementIn(..., elements))
    .orElse(Collections.emptyList());
    Without Optional:
    List otherElements;
    if (potentiallyNullOrEmptyList == null || potentiallyNullOrEmptyList.isEmpty()) {
    otherElements = Collections.emptyList();
    } else {
    otherElements = repository.findAllByXXAndWhereElementIn(..., potentiallyNullOrEmptyList));
    }

    • @MikesTechCorner
      @MikesTechCorner  3 місяці тому +1

      If you get a List declard object from somewhere and it is null then you should have had an empty list instead. That is the thought behind not wrapping Lists in optionals. Lists are already wrappers.

    • @r2-p2
      @r2-p2 3 місяці тому +1

      @@MikesTechCorner Except if the empty list has a different meaning than no list.

    • @MikesTechCorner
      @MikesTechCorner  3 місяці тому

      @@r2-p2then you should change the meaning so there is always a list. Use real readable logic to handle the situation where you had a "null" list.