Gautham M
Gautham M

Reputation: 4935

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?

Upvotes: 2

Views: 753

Answers (1)

Holger
Holger

Reputation: 298123

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.

or

or

or

Upvotes: 9

Related Questions