Shortcut for null-check before method invocation in java

Raphael Tarita :

When writing simple or complex java code, it seems quite common to write code like this:

if (obj != null) {
    obj.someMethod();
}

Or more specific:

Foo someValue = null;
if (valueObject != null) {
    someValue = valueObject.getSomeValue();
}

Which would mean someValue stays null when the Value Object is null. Now, as I encounter this type of code quite often (and it increases cognitive/cyclic complexity), I wondered if there is some way to simplify these statements in any way. I looked for a solution which looks like:

Foo someValue = nullOrCompute(valueObject, valueObject::getSomeValue);

After some research it seemed that Java does not provide a similar feature. So, as a test, I wrote the shortcut myself, which looks like this:

public class NullHelper
{
    private static <T> boolean check(T object)
    {
        return object == null;
    }

    public static <T> void nullOrExecute(T object, Consumer<T> func)
    {
        if (!check(object))
            func.accept(object);
    }

    public static <T, R> R nullOrCompute(T object, Function<T, R> func)
    {
        return check(object)
            ? null
            : func.apply(object);
    }

    public static <T, P0, R> R nullOrCompute(T object, BiFunction<T, P0, R> func, P0 param0)
    {
        return check(object)
            ? null
            : func.apply(object, param0);
    }

    // more params
}

Note that you'd have to write your own "NFunction" Interfaces if you wanted to include versions with more params because Java does not provide TriFunctions or higher.

My Question is:

Is this code a good way to simplify a big existing codebase? And if not, is it because there is a more convenient Java feature which I don't know, or is it beacuse I need to improve my custom version (and how)?

Please keep in mind that I am not talking about the most convenient solution in general, but for a solution that can be applied to a big existing codebase.

Thank you in advance.

Malt :

Your code:

check(foo)
nullOrExecute(foo, consumer)
nullOrCompute(foo, mapper)
nullOrCompute(foo, func, param)

Equivalent code using optionals:

Optional.ofNullable(foo).isPresent();
Optional.ofNullable(foo).ifPresent(consumer);
Optional.ofNullable(foo).map(mapper)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324338&siteId=1