Consider a batch operation that may or may not take long time to do its job (depends on data). A user can register an OPTIONAL listener for tracking job progress.
NOTE: listener registration is totally optional and user may want to call the job without registering any listener.
Q: Which of the following solutions are your preference and why?
EDIT: the concern here is performance vs clean code. some say, checking null reference (solution 1) is faster compare to second solution. but second solution is cleaner and more understandable. I would like to have your opinion.
No 1: Allow null listener and always check if listener is not null, then call it.
doMyBatchJob() {
if (listener != null) {
listenr.progressStarted(params);
}
while (x) {
if (listener != null) {
listener.progressUpdated(current, expected)
}
}
if (listener != null) {
listenr.progressFinished(params);
}
}
No 2: Implement a dummy listener, and register it if user didn't pass his/her own listener. so that can call listener without checking for null object.
DummyListener {
public void progressStarted(params) { //DO NOTHING }
public void progressUpdated(current, expected) { //DO NOTHING }
public void progressFinished(params) { //DO NOTHING }
}
doMyBatchJob() {
listener.progressStarted(params);
while (x) {
//Do a single unit of the batch operation
// ... code omitted here
listener.progressUpdated(current, expected)
}
listener.progressFinished(params)
}