Possible redundant object creation with Optional#ofNullable?

Jin Kwon

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?
JB Nizet
  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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Access object current during creation possible?

From Dev

Is it possible to override the creation of a new object and return an existing object?

From Dev

Could it be possible to observe an intermediate state of a final array during object creation?

From Dev

Redundant Object.ToString

From Dev

Does object creation of subclass create object of superclass, if yes Is it possible to access it in subclass?

From Dev

Is it possible to skip separate object creation in Python OOP and create the object when class function is called?

From Dev

Android Lint warning: "Redundant array creation for calling varargs method"

From Dev

Is it possible to have a redundant S3 bucket?

From Dev

Understanding effective object creation

From Dev

order of object creation, cpp

From Dev

C# - Object Creation

From Dev

Global object and creation order

From Dev

Java object creation and referencing

From Dev

Python Method object creation

From Dev

Object creation optimization

From Dev

Tracking Object Creation in Android

From Dev

PHP Object creation Looping

From Dev

Peculiar way for object creation?

From Dev

Wrapper Object Explicit Creation

From Dev

Expect the creation of a new object

From Dev

Swift: Dynamic Object Creation

From Dev

Unspecified Implicit Object Creation

From Dev

Kubernetes object creation time

From Dev

Object creation method confused

From Dev

Java object creation and referencing

From Dev

Infinite loop object creation

From Dev

Mutex for object creation

From Dev

iOS dynamic object creation

From Dev

Object creation optimization