-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Description
The Story
Expect a singleton dialog instance which will be opened by the user on a specific button click.
This singleton dialog instance registers on the eventbus when the dialog starts to show.
What the developer now has to consider is to check if the dialog instance is already registered.
Otherwise an exception will be thrown which is a common pitfall.
It brings the application into an unecessary error state.
And it leads to boiler plate code which itself leads to bad design, because developers have to implement:
if (!eventBus.isRegistered(object)) {
eventBus.register(object);
}
and
if (eventBus.isRegistered(object)) {
eventBus.unregister(object);
}
Solution Proposal
Why not implementing the register and unregister methods like this:
/**
* Registers on event bus.
*
* @param object the object to register
* @return true if the object is registered successfully, false if the object was already registered.
*/
public boolean registerBetter(final Object object) {
if (!isRegistered(object)) {
register(object);
return true;
}
return false;
}
/**
* Unregisters on event bus.
*
* @param object the object to unregister
* @return true if the object unregistered successfully, false if the object was not registered before.
*/
public boolean unregisterBetter(final Object object) {
if (isRegistered(object)) {
unregister(object);
return true;
}
return false;
}
With that solution developers can just call register, and they don't have to consider the internal state of the event bus.
Because the internal state of the event bus framework is something that the framework should handle, not the developer who is using it.