javaoption-typepremature-optimization

Possible redundant object creation with Optional#ofNullable?


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));

Solution

    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.