gravitino
gravitino copied to clipboard
[Improvement] Refactor EventBus#dispatchEvent
What would you like to be improved?
Current implementation lacks elegance.
- The current implementation hardcodes the supported event types. Whenever a new event type (e.g., ErrorEvent, AuditEvent) is added, the dispatchEvent method must be modified.
- If the number of event types increases or becomes more granular in the future, it's easy to miss handling certain branches.
public void dispatchEvent(BaseEvent event) {
Consumer<BaseEvent> handler = dispatcherMap.get(event.getClass());
if (handler != null) {
handler.accept(event);
} else {
throw new IllegalArgumentException("Unsupported event type: " + event.getClass().getName());
}
}
How should we improve?
A more elegant approach should be used—one that allows each event to determine its own handling logic, eliminating the need for hardcoded type checks and avoiding missing branches. This way, potential issues can be caught at compile time.