Reputation: 4935
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
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.
Objects.requireNonNull(T obj, String message)
vsObjects.requireNonNull(T obj, Supplier<String> messageSupplier)
or
Objects.requireNonNullElse(T obj, T defaultObj)
vsObjects.requireNonNullElseGet(T obj, Supplier<? extends T> supplier)
or
or
log(System.Logger.Level level, String msg)
vslog(System.Logger.Level level, Supplier<String> msgSupplier)
Upvotes: 9