0

I'm curious about a usage of Optional.

With following code snippet,

public List<Some> read(
    @QueryParam("first_result") @Min(0)
    final Integer firstResult,
    @QueryParam("max_results") @Min(0)
    final Integer maxResults) {

    // ...

    if (firstResult != null) {
        query.setFirstResult(firstResult);
    }

    // ...
}

When I change the code like this,

ofNullable(firstResult).ifPresent(v -> query.setFirstResult(v));
  • Question 1: Does ofNullable obviously creates a redundant object?
  • Question 2: Is it worth for avoiding a boiler-plate code?
  • Question 3: Is this question talking about premature optimization?
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

2 Answers2

3
  1. Yes
  2. It's a matter of opinion. I personally find the code using an if block more readable, and not really more verbose
  3. Yes. The cost of creating a short-lived Optional object is negligible, especially compared with executing a JPA query. So, if you find the optional-based code more readable and elegant, you shouldn't worry about performance.
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Another option is to prevent firstResult from becoming null in the first place, so you won't have to check for it and you can avoid easy mistakes.

How to do it? here are some options:

  • If firstResult is the result of a method, code that method in a way that is guaranteed to never return null (and add unit tests to check it).

  • Change the type of the field from Integer to Optional<Integer>, this way it becomes clear to the reader that this field is optional and he must check it before using it.

  • Change the return type of the method that writes to firstResult so that it returns Optional<Integer>, and finish that method with return Optional.ofNullable(result). This way the code that receives the result, must check the return value before storing it in the field, preventing it from becoming null.

There may be other ways.

ESala
  • 6,878
  • 4
  • 34
  • 55