Avoiding 'instanceof' in Java - java

I have the following (maybe common) problem and it absolutely puzzles me at the moment:
There are a couple of generated event objects which extends the abstract class Event and I want to divide them to Session Beans, like
public void divideEvent(Event event) {
if (event instanceof DocumentEvent) {
documentGenerator.gerenateDocument(event);
} else if (event instanceof MailEvent) {
deliveryManager.deliverMail(event);
...
}
...
}
But there could be more than two event types in future, so the if-else will be long and maybe unreadable. Additionally I think instanceof is not really "best practice" in this case.
I could add an abstract method to the Event type and have them divide itself but then I have to inject the specific Session Beans within each entity.
Is there any hint to achieve a "pretty" solution for this problem?
Thanks for any help!

The simplest approach is to have the Event provide a method you can call so the Event knows what to do.
interface Event {
public void onEvent(Context context);
}
class DocumentEvent implements Event {
public void onEvent(Context context) {
context.getDocumentGenerator().gerenateDocument(this);
}
}
class MailEvent implements Event {
public void onEvent(Context context) {
context.getDeliveryManager().deliverMail(event);
}
}
class Context {
public void divideEvent(Event event) {
event.onEvent(this);
}
}

Polymorphism is your friend.
class DocumentGenerator {
public void generate(DocumentEvent ev){}
public void generate(MainEvent ev){}
//... and so on
}
Then just
DocumentGenerator dg = new DocumentGenerator();
// ....
dg.generate(event);
Update
A number of people have raised the objection that you "have to know the kinds of event at compile time." And, yes, you clearly have to know what events you're interpreting at compile time of the generator part, when else would you be able to write the generating part?
These competing examples use Command pattern, which is fine, but means Events have to know the details not just of their representation but of how to print their representation. That means each class may have two kinds of requirements changes to which their sensitive: changes in what events represent, and changes in the way the events are represented in print.
Now, consider, for example, needing to internationalize this. In the Command-pattern case, you have to go to n classes for n different Event types and write new do methods. In the polymorphism case, the changes are localized to one class.
Naturally if you need to internationalize once, you may need many languages, which drive you to adding something like a Strategy to each class in the Command-pattern case, requiring now n classes × m languages; again, you need only have one strategy and one class in the polymorphism case.
There are reasons to choose either approach, but to claim the polymorphism approach is wrong is just incorrect.

Each event has a function, say do.
Each subclass overrides do, to do (:P) the appropriate action.
Dynamic dispatch does everything else afterwards.
All you need to do, is call event.do()

I have no commenting rights and i dont know the exact answer. But is it just me or some ppl here suggest using overloading (which happens at compile time and therefore just generate compile error) to solve this problem?
Just an example. As you see, it will not compile.
package com.stackoverflow;
public class Test {
static abstract class Event {}
static class MailEvent extends Event {}
static class DocEvent extends Event {}
static class Dispatcher {
void dispatchEvent(DocEvent e) {
System.out.println("A");
}
void dispatchEvent(MailEvent e) {
System.out.println("B");
}
}
public static void main(String[] args) {
Dispatcher d = new Dispatcher();
Event e = new DocEvent();
d.dispatchEvent(e);
}

What's the problem with exploiting the method resolution order?
public void dispatchEvent(DocumentEvent e) {
documentGenerator.gerenateDocument(event);
}
public void dispatchEvent(MailEvent e) {
deliveryManager.deliverMail(event);
}
Let Java do the work of matching the correct argument type, then just dispatch the event properly.

This is a typical use case for Sum types, also known as tagged unions. Unfortunately, Java does not support them directly, so they have to be implemented using some variation of the visitor pattern.
interface DocumentEvent {
// stuff specific to document event
}
interface MailEvent {
// stuff specific to mail event
}
interface EventVisitor {
void visitDocumentEvent(DocumentEvent event);
void visitMailEvent(MailEvent event);
}
class EventDivider implements EventVisitor {
#Override
void visitDocumentEvent(DocumentEvent event) {
documentGenerator.gerenateDocument(event);
}
#Override
void visitMailEvent(MailEvent event) {
deliveryManager.deliverMail(event);
}
}
Here we have defined our EventDivider, now to provide a dispatch mechanism:
interface Event {
void accept(EventVisitor visitor);
}
class DocumentEventImpl implements Event {
#Override
void accept(EventVisitor visitor) {
visitor.visitDocumentEvent(new DocumentEvent(){
// concrete document event stuff
});
}
}
class MailEventImpl implements Event { ... }
public void divideEvent(Event event) {
event.accept(new EventDivider());
}
Here I used maximum possible separation of concerns so that responsibility of each class and interface is one and only one. In real life projects DocumentEventImpl, DocumentEvent implementation and DocumentEvent interface declaration are usually merged into a single class DocumentEvent, but that introduces circular dependencies and forces some dependencies between concrete classes (and as we know, one should prefer to depend on interfaces).
Additionally, void should usually be replaced with a type parameter to represent the result type, like this:
interface EventVisitor<R> {
R visitDocumentEvent(DocumentEvent event);
...
}
interface Event {
<R> R accept(EventVisitor<R> visitor);
}
This allows one to use stateless visitors, which are very nice to deal with.
This technique allows to (almost?) always eliminate instanceof mechanically rather than having to figure out a problem-specific solution.

You could register each of your handler classes against each event type, and perform dispatch when event happens like this.
class EventRegister {
private Map<Event, List<EventListener>> listerMap;
public void addListener(Event event, EventListener listener) {
// ... add it to the map (that is, for that event, get the list and add this listener to it
}
public void dispatch(Event event) {
List<EventListener> listeners = map.get(event);
if (listeners == null || listeners.size() == 0) return;
for (EventListener l : listeners) {
l.onEvent(event); // better to put in a try-catch
}
}
}
interface EventListener {
void onEvent(Event e);
}
And then get your specific handlers to implement the interface, and register those handlers with the EventRegister.

You could have a Dispatcher interface, defined like
interface Dispatcher {
void doDispatch(Event e);
}
with implementations like DocEventDispatcher, MailEventDispatcher, etc.
Then define a Map<Class<? extends Event>, Dispatcher>, with entries like (DocEvent, new DocEventDispatcher()). Then your dispatch method could be reduced to:
public void divideEvent(Event event) {
dispatcherMap.get(event.getClass()).doDispatch(event);
}
Here's a unit test:
public class EventDispatcher {
interface Dispatcher<T extends Event> {
void doDispatch(T e);
}
static class DocEventDispatcher implements Dispatcher<DocEvent> {
#Override
public void doDispatch(DocEvent e) {
}
}
static class MailEventDispatcher implements Dispatcher<MailEvent> {
#Override
public void doDispatch(MailEvent e) {
}
}
interface Event {
}
static class DocEvent implements Event {
}
static class MailEvent implements Event {
}
#Test
public void testDispatcherMap() {
Map<Class<? extends Event>, Dispatcher<? extends Event>> map = new HashMap<Class<? extends Event>, Dispatcher<? extends Event>>();
map.put(DocEvent.class, new DocEventDispatcher());
map.put(MailEvent.class, new MailEventDispatcher());
assertNotNull(map.get(new MailEvent().getClass()));
}
}

Related

What java design pattern to avoid casting data entity

I'm currently implementing asynchronous-like event queue inside my application - it is designed to work like this: one component reacts to some user input and putting event to the queue, and another "listener" is checking whether there is event of specific type inside the queue and run it's own business logic
There can be various event types (like USER_MOUSE_CLICK, USER_KEYBOARD_CLICK etc) and every implementation has it's own "event-object" type
It looks like this (I'm ommiting constructors - setting all fields and getters/setters - they are just normal default ones):
public abstract MyEvent<T> {
private EventType eventType;
private T eventData;
}
public MouseClickEvent extends MyEvent<ClickPoint> { // ClickPoint class contains x,y of mouse click
public MouseClick(ClickPoint point) {
super(EventType.USER_MOUSE_CLICK, point);
}
}
public KeyboardClickEvent extends MyEvent<String> { // character that has been clicked on keyboard
public MouseClick(String key) {
super(EventType.USER_KEYBOARD_CLICK, key);
}
}
I have also a service with queue of MyEvent instances and the method to retrieve first event of provided EventType if exists - it's look like
...
private List<MyEvent> queue;
...
public MyEvent fetchMyEvent(EventType eventType) {
for(MyEvent event : queue) {
if(event.getEventType().equals(eventType) {
return event;
}
}
return null;
}
...
The problem is that when I'm trying to retrieve the event I need to cast it to specific implementation like
// some listener logic
MouseClickEvent event = (MouseClickEvent ) eventService.fetchMyEvent(EventType.USER_MOUSE_CLICK);
log("The X point of mouse click was: " + event.getEventData().x);
I don't like this casting - I feel like I have no control of a types when I'm fetching events and I see this situation like a 'weak point' and bug generator. Is there any design pattern to avoid this, or should I redesign whole system? Or maybe this is the only way and I should not care
I would suggest you the visitor pattern to avoid cast. You are right casting should be used with precaution.
To use visitor pattern you have to :
first: define the visitor interface:
public interface IEventVisitor {
void visit(MouseClickEvent event);
void visit(KeyboardClickEvent event);
}
Second in your supper class define an absract method accept as:
public abstract MyEvent<T> {
private EventType eventType;
private T eventData;
public abstract void accept(IEventVisitor visitor);
}
Third: implement the method for each subclass as:
public MouseClickEvent extends MyEvent<ClickPoint> { // ClickPoint class contains x,y of mouse click
public MouseClick(ClickPoint point) {
super(EventType.USER_MOUSE_CLICK, point);
}
public void accept(IEventVisitor visitor) {
visitor.visit(this);
}
}
And finally implement your visitor interface.
The use will be like the following, instantiate the visitor and call event.accept(visitor).
Event event = eventService.fetchMyEvent(EventType.USER_MOUSE_CLICK);
IEventVisitor visitor = new IEventVisitor() {
#Override
public void visit(MouseClickEvent event) {
// logic goes here
}
#Override
public void visit(KeyboardClickEvent event) {
// logic goes here
}
};
event.accept(visitor);

Best approach to deal with subclasses in a List with separate dependencies

In doing some restructuring on a project of mine, I've been attempting to better utilise object oriented concepts in my code but I'm not sure how to structure this particular situation:
A method can trigger one of three possible "events", with each event having a dependency on a particular type (Player, Block, World) which needs to happen at runtime as they are deserialised from a file. In an attempt to simplify the execution path I structured it like this so they can all be part of a List which just executes a single method:
public interface IEvent {
void trigger();
}
public class PlayerEvent implements IEvent {
private Player player;
public void passPlayer(Player player){
this.player = player;
}
public void trigger(){
// player does things
}
}
public class BlockEvent implements IEvent {
private Block block;
public void passBlock(Block block){
this.block = block;
}
public void trigger(){
// block does things
}
}
However, since each event is dependent on a Player or Block depending on its type, I would have to iterate over the list and downcast each object using instanceof to pass the relevant dependency.
public void executeEvents(){
for(IEvent event : events){
if(event instanceof PlayerEvent){
((PlayerEvent) event).passPlayer(player);
} else {
((BlockEvent) event).passBlock(block);
}
event.trigger();
}
}
I read that downcasting should never be done under any circumstances, so I've been wondering what alternatives I could use that would follow a similar simple execution path but falls under good OOP practice? Or should I just eliminate the interface altogether and have a separate List for each event type?
I read that downcasting should never be done under any circumstances,
so I've been wondering what alternatives
I would not generalize. Applications/libraries that generate code or use reflection generally may use downcast.
In other cases, downcast should indeed be avoided.
You have multiple ways to achieve your goals without downcasting.
1) Don't manipulate a too broad type in the List. Additionally you could make IEvent a generic interface and generalize passPlayer() and passBlock() in pass() that you will move up in the interface.
The interface could look like :
public interface IEvent<T> {
void trigger();
void pass(T t);
}
And implementation of it could look like :
public class PlayerEvent implements IEvent<Player> {
private Player player;
public void trigger() {
// player does things
}
#Override
public void pass(Player t) {
}
}
Now with a more specific typed List you could write :
private Player player = ...;
public void executeEvents() {
List<IEvent<Player>> events = ...;
for (IEvent<Player> event : events) {
event.pass(player);
}
}
2) Use the visitor pattern to benefit from a double dispatch.
Event -> Visitor -> processing.
Each pass() method become a method of the Visitor.
You could enrich the IEvent interface to add an accept() method that accepts a Visitor :
public interface IEvent {
void trigger();
void accept(Visitor visitor);
}
Here the Visitor interface and implementation :
Visitor interface
public interface Visitor {
void visitBlockEvent(BlockEvent block);
void visitPlayerEvent(PlayerEvent player);
}
Visitor implementation
public class ProcessEventVisitor implements Visitor {
private Player player;
private Block block;
#Override
public void visitBlockEvent(BlockEvent blockEvent) {
// do your processing
}
#Override
public void visitPlayerEvent(PlayerEvent playerEvent) {
// do your processing
}
}
IEvent subclasses delegate now to the Visitor parameter the processing :
public class PlayerEvent implements IEvent{
public void trigger() {
// player does things
}
#Override
public void accept(Visitor visitor) {
visitor.visitPlayerEvent(this);
}
}
And the client code can now look like :
private Player player;
public void executeEvents() {
List<IEvent> events = ...;
ProcessEventVisitor visitor = new ProcessEventVisitor();
for (IEvent event : events) {
event.accept(visitor);
}
}

Java: How can I design this class for having optional generics ParameterType?

I have this class in my code
public abstract class MyAbstractEventListener<E extends IMyEvent> {
public abstract void handleEvent(E e);
}
and I can make instances in this way (let's call it A):
new MyAbstractEventListener<IMyEvent>() {
#Override
public void handleEvent(final IMyEvent e) {
// Method implementation
}
};
But for my purposes, it would be ideal being able also to do this as well when there's no required event info (let's call this B):
new MyAbstractEventListener() { // Or receiving some unused parameter
#Override
public void handleEvent() {
// Method implementation
}
};
without having the warning about the class being raw and reccomending to parameterize it.
To clarify, I want the class to allow either the A or B instantiation, having the personal choice of using the one I prefer each time. If there's some generics parameter, the method receiving the IMyEvent object and if not, the method without parameters.
An example of code using this class would be:
EventBus.getInstance().addEventListener("some.string", new
AbstractEventListener<IMyEvent>() {
#Override
public void handleEvent(final IMyEvent e) {
// Sometimes does use 'e', sometimes doesn't. That's the point
MyConfirmationWindow.showConfirmationWindow(MyWindowType.WARNING, "kk", "lll");
}
});
Is there a way? Any link or resource will be appreciated.
Well, you could make an abstract subclass :
public abstract class BlindListener extends MyAbstractEventListener<IMyEvent> {
public abstract void handleEvent();
#Override
public void handleEvent(IMyEvent iMyEvent) {
handleEvent(); // delegate to abstract method that ignores the argument
}
}
This is actually a class that uses generics, but clients won't ever have to deal with them :
new BlindListener() {
#Override
public void handleEvent() {
}
}
Instances that do need a specific type can still use the MyAbstractEventListener directly
I don't think you will be able to avoid having tow handleEvent methods the way you described here.
But here is another approach using Null Object design pattern and single handleEvent method:
new MyAbstractEventListener<IMyEvent>() {
#Override
public void handleEvent(final IMyEvent e) {
// Method implementation
}
};
new MyAbstractEventListener<NullIMyEvent>() {
#Override
public void handleEvent(final NullIMyEvent e) {
// Method implementation
}
};
public interface IMyEvent{}
public class NullIMyEvent implements IMyEvent{}
public static abstract class MyAbstractEventListener<E extends IMyEvent> {
public abstract void handleEvent(E e);
}
public abstract class MyAbstractEventListener<E extends IMyEvent> {
But for my purposes, it would be ideal being able also to do this as well when there's no required event info (let's call this B):
The question is: what does the class MyAbstractEventListener do with the information that the parameter type E extends IMyEvent? Is there any method in that class working on type IMyEvent?
If not you could simple remove extends IMyEvent to achieve your goal.
Otherwise you need a different class since MyAbstractEventListener relies on type Eextending (or implementing) IMyEvent.

Events with different types and data

I am writing a library in Java, which throws an event of different types with differing data depending on the type.
For example, here is the extended EventObject:
public class FooEvent extends EventObject {
private final int eventType;
private final Object fooEventObject;
public FooEvent(int type, Object obj){/*...*/}
public int getEventType() {/*...*/}
public int getEventObject() {/*...*/}
}
And here is how I my listener currently looks like:
FooEventListener listener = new FooEventListener() {
#Override
public void onDataChange(FooEvent event) {
switch(event.getEventType()) {
case EVENT_TYPE_BAR:
Bars bar = (Bars)event.getEventObject();
/*work with Bar object...*/
break;
case EVENT_TYPE_GOO:
Goo goo = (Goo)event.getEventObject();
/*work with Goo object...*/
break;
/* etc ...*/
}
}
}
I would like to know if this is the right way of solving this problem (although I doubt it is, since the user of the library would need to know what type to cast to) wherein I have different event types with objects and I do not want to go and make a different event & listener for each one.
Guava's EventBus provides a slightly different approach that can handle multiple event types.
There is unfortunately no easy solution to have a type safe event system with different types. You either have to have 1 listener / publishing implementation per type of you need to teach one side about all the event types that exist.
There is a way to remove the need for instanceof or switch (type) and casting though: the Visitor Pattern
The pattern uses the fact that event objects know their own type which means they can call the right method. The downside is that you need a listener interface that contains all the types.
public class Test {
abstract static class EventObject {
protected abstract void deliver(EventListener listener);
}
static class AEvent extends EventObject {
#Override
protected void deliver(EventListener listener) {
listener.onAEvent(this);
}
}
static class BEvent extends EventObject {
#Override
protected void deliver(EventListener listener) {
listener.onBEvent(this);
}
}
interface EventListener {
void onAEvent(AEvent event);
void onBEvent(BEvent event);
// ...
}
private static final EventListener LISTENER = new EventListener() {
#Override
public void onBEvent(BEvent event) {
System.out.println("Got B Event! " + event);
}
#Override
public void onAEvent(AEvent event) {
System.out.println("Got A Event! " + event);
}
};
private static void notifyListeners(EventObject event) {
event.deliver(LISTENER);
}
public static void main(String[] args) {
notifyListeners(new AEvent());
notifyListeners(new BEvent());
}
}
A better way to solve this is with generics.
public class FooEvent<T> extends EventObject {
private final T fooEventObject;
public FooEvent(T obj){/*...*/}
public T getEventObject() {/*...*/}
}
//usage
SomeType object = new SomeType();
new FooEvent<SomeType>(object);
I think it's a way to go, but not the cleanest way. You should create an abstract class
public abstract class AbstractEventType<T> extends EventObject {}
and extend from that:
public abstract class FooEvent extends AbstractEventType<Foo> {}
public abstract class BarEvent extends AbstractEventType<Bar> {}
Then you need to fire different events and also have different event listeners based on the type:
public interface FooEventListener {
public void onFooChange(FooEvent fooEvent);
}
etc.
If you want to stick with only one event type then you could at least move the code to determine the type to your framework and avoid pollution of the "business" code, by creating one handler method per type, e.g.
public interface MyEventListener {
public void onFooChange(EventType<Foo> eventType);
public void onBarChange(EventType<Bar> eventType);
}

Multiple observable events for one observable

I'm trying to get around the ugly conditional casting involved when interpreting an update() call for an observable that will want to notify its observers of multiple types of events. Also, I'd prefer not to pass flags to the notifyObservers()/update() method.
I do not want the observers to have to poll the observable object to find out what's changed, I'd like this new data to be given to the observers via the update() method (or similar.)
I have an idea for a solution. I instanciate one observable object for each type of notification. For example: The observable is an object representing a hardware device, it will contain observables representing its state:
public final Observable connectionState = new Observable();
public final Observable dataState = new Observable ();
This way, observers don't need to do any sort of querying or conditional casting, as one observer, i.e. one overridden update() method can be used per notification type.
After much frustration this is the most elegant solution I can think of, however I have this horrible feeling that I've missed the point about how to use Observers/Observables properly.
My main issues with that solution are:
It still involves a cast (at least it's not conditional)
Since the observables need to be observable, they must be public members. While this does allow observers to call addObservable(), it also allows them to call notifyObservers().
Am I doing the right thing?
Thanks
You are struggling with the limitations of the Java 1.0 implementation of the Observer pattern. Take a look at this answer to the question Is java.util.Observable used anywhere?
They are not used, because their
design is flawed: they are not type
safe. You can attach any object that
implements Observer to any Observable,
which can result in subtle bugs down
the line.
Wrapping them inside a type safe
interface is about the same amount of
work as implementing the pattern from
scratch, so I guess the latter is
preferred in most cases.
Rather than trying to shoehorn your requirements into java.util.Observer, maybe you should just implement your own version of the pattern that better fits your needs.
You can try to use Observable paired together with Visitor pattern:
class MyObserver implements Observer, EventVisitor {
public void update(Observable o, Object arg) {
((EventAcceptor) arg).accept(this);
}
public void visit(SomeEvent v) {
System.out.println("SomeEvent: " + v.s);
}
public void visit(AnotherEvent v) {
System.out.println("AnotherEvent: " + v.info);
}
}
interface EventVisitor {
void visit(SomeEvent v);
void visit(AnotherEvent v);
}
interface EventAcceptor {
void accept(EventVisitor v);
}
class SomeEvent implements EventAcceptor {
public final String s;
public SomeEvent(String s) {
this.s = s;
}
public void accept(EventVisitor v) {
v.visit(this);
}
}
class AnotherEvent implements EventAcceptor {
public final String info;
public AnotherEvent(String info) {
this.info = info;
}
public void accept(EventVisitor v) {
v.visit(this);
}
}
class MyObservable extends Observable {
void handleSomeEvent() {
setChanged();
notifyObservers(new SomeEvent("some event"));
}
void handleAnotherEvent() {
setChanged();
notifyObservers(new AnotherEvent("some event"));
}
}
class Sample {
public static void main(String[] args) {
MyObservable observable = new MyObservable();
observable.addObserver(new MyObserver());
observable.handleSomeEvent();
observable.handleAnotherEvent();
}
}
There are lots of possible solutions for your problem. If you feel the Observable class isn't suited to your problem you can maintain your own collection of listeners.
interface Listener {
void onEvent1(Type1 arg);
void onEvent2(Type2 t2, Type3 t3);
void onEvent3();
}
List<Listener> listeners = new CopyOnWriteArray<Listener>();
public void addListener(Listener l) { listeners.add(l); }
public void onEvent1(Type1 arg) {
for(Listener l: listeners) l.onEvent1(arg);
}

Categories