mercredi 6 avril 2016

Dynamic dispatch without instanceof or getClass() in Java

I have the following domain objects:

public interface Event {}

public class FirstEvent {}

public class SecondEvent {}

Then I have another module, that should be fully decoupled from my domain objects, meaning that it knows domain objects, but domain objects should not know about existence of this additional module.

In this module I receive objects through common interface Event and I need to act differently based on specific event type.

Currently my code looks like that

if (event instanceof FirstEvent.class) {
    doFirst();
else if (event instanceof SecondEvent.class) {
    doSecond();
}

It works fine, but static analysis tools and code reviewers complain that I should not use instanceof and I should replace it with more object-oriented approach. Reflection or getClass() is also not an option.

How to do that in Java?

I've reviewed many existing questions about replacements of instanceof but all of them suggested adding some logic straight into domain objects. However, in this case I don't want to pollute them with logic specific to just my module.

Aucun commentaire:

Enregistrer un commentaire