Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional object creation using java Supplier interface

I have a method as below:

void updateObject(ObjOne obj, SomeClass data) {
    if(obj != null) {
        obj.doSomething(data);
    }
}

The updateObject is called many times and to avoid null check at each place, I thought of avoiding the below:

// directly invoke doSomething conditionally.
if(obj != null) {
    SomeClass data = getData();
    obj.doSomething(data);
}

Since data is used only when obj is non null, I thought of refactoring the code as below:

void updateObject(ObjOne obj, Supplier<SomeClass> data) {
    if(obj != null) {
        obj.doSomething(data.get());
    }
}

This would create an object of SomeClass only when required, but instead creates an object of Supplier type.

Is the above approach using Supplier better?

like image 792
Gautham M Avatar asked Mar 01 '26 06:03

Gautham M


1 Answers

The performance depends on the costs of the construction of the SomeClass instance, in other words, what you can save when only creating a Supplier and never a SomeClass instance, and the likelihood of not creating the SomeClass instance. If the SomeClass instance is created anyway in most cases, you obviously can’t save anything by additionally creating a Supplier.

If you are designing an API without knowing the expenses and likelihoods, you may offer both methods and let the caller decide which to use. That is an established pattern, e.g.

  • Objects.requireNonNull​(T obj, String message) vs
  • Objects.requireNonNull​(T obj, Supplier<String> messageSupplier)

or

  • Objects.requireNonNullElse​(T obj, T defaultObj) vs
  • Objects.requireNonNullElseGet​(T obj, Supplier<? extends T> supplier)

or

  • Optional.orElse​(T other) vs
  • Optional.orElseGet​(Supplier<? extends T> supplier)

or

  • log​(System.Logger.Level level, String msg) vs
  • log​(System.Logger.Level level, Supplier<String> msgSupplier)
like image 119
Holger Avatar answered Mar 02 '26 21:03

Holger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!