applyIfNonNull looks to be a version of Optional without the Optional object. The following is the same as suggested but with an additional Optional object:

    Optional.ofNullable(valueX).ifPresent(bean::setValue);
Optional.ofNullable(valueX).ifPresent(v -> someObject.compute(v, "bar"));

Or, combined:

    Optional.ofNullable(valueX).ifPresent(v -> {
        bean.setValue(v);
        someObject.compute(v, "bar");
    });

The new method is shorter and saves the Optional object, so it may have some value. I think I've even written the applyIfNonNull method myself several times.


On 28/12/2020 15:39, Gary Gregory wrote:
Hi Bindul,

Let's see what this would look like with a PR :-)

Gary

On Mon, Dec 28, 2020, 01:23 Bindul Bhowmik <bindulbhow...@gmail.com> wrote:

Hi,

I would like to propose an enhancement to the ObjectUtils class in lang:

Background: I have seen multiple places in code where we have to check
if a value is null before using it in a setter or other method, like:

     if (valueX != null) {
         bean.setValue(valueX);
        someObject.compute(valueX, "bar");
     }

I was wondering if there is interest to add a method like the
following in ObjectUtils:

     public static <T> void applyIfNonNull(final Consumer<T> consumer,
final T object)
     public static <T> void applyFirstNonNull(final Consumer<T>
consumer, final T... objects)

With this the two statements above could be applied as:

     ObjectUtils.applyIfNonNull(bean::setValue, valueX);
     ObjectUtils.appyIfNonNull(v -> someObject.compute(v, "bar"), valueX);

Of course, the benefit of this increases with more such null checks we
need in the code that can be replaced by single statements.

I am happy to open a JIRA and GH pull request if there is interest in
this minor enhancement.

Bindul

---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscr...@commons.apache.org
For additional commands, e-mail: dev-h...@commons.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscr...@commons.apache.org
For additional commands, e-mail: dev-h...@commons.apache.org

Reply via email to