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?