I have code similar to this in all my observer classes that handle events fired by an event bus class.
As you can see there are a lot of instanceof checks to choose the path of action needed to appropriately handle events, and I was wondering if this could be done more cleanly, eliminating the instanceof tests?
@Override
public void handleEvent(Event event) {
if (event instanceof DownloadStartedEvent) {
DownloadStartedEvent dsEvent = (DownloadStartedEvent)event;
dsEvent.getDownloadCandidateItem().setState(new BusyDownloadingState());
} else if (event instanceof DownloadCompletedEvent) {
DownloadCompletedEvent dcEvent = (DownloadCompletedEvent)event;
dcEvent.getDownloadCandidateItem().setState(new FinishedDownloadingState());
DownloadCandidate downloadCandidate = dcEvent.getDownloadCandidateItem(). getDownloadCandidate();
if (downloadCandidate.isComplete()) {
// start extracting
}
} else if (event instanceof DownloadFailedEvent) {
DownloadFailedEvent dfEvent = (DownloadFailedEvent)event;
dfEvent.getDownloadCandidateItem().setState(new FailedDownloadingState());
}
}
You could eliminate the events by adding listeners for each event in turn. Consider for instance
You may also consider combining Completed/Failed into a single event since it looks like you already have an isCompleted method. You could handle CompleteEvent and check for success. If successful you could start extracting otherwise you could set your failure state.
My other thought would be why are you setting a new object as a state indicator. Could that perhaps be better served using constants/enum values?