lundi 11 septembre 2023

How do I refactor this code with if/else for Update/Delete event and the class is injected using Guice

I'm trying to refactor one of the classes we have which is very long. The class is a listener which has only two events Update and Delete. We started with just this

public class DocumentListener implements Listener
{
    @Inject
    public DocumentListener(// a bunch of injected parameters) {

    }

    public void receive(Event event)
    {
        Phase phaseWhenReceived = phase_;
        if (event instanceof UpdateEvent) {
            // do update
        } else if (event instanceof EntityDeleteEvent) {
            // do delete
        } else if (event instanceof PhaseEvent) {
            // do nothing for now.
        } else {
            LOGGER.warn("Received unknown event type : " + event.getClass().getName());
        }
    }
}

The class grew to be over 2000 lines long which naturally we want to have two classes; Update and Delete. However, the class is binded with Guice like this.

bind(DocumentListener.class).in(SINGLETON);

I started changing the class to be abstract class and then created Update and Delete classes to extract the behaviors.

But if I do this

public abstract DocumentListener implements Listener
{
    public DocumentListener(// a bunch of injected parameters) {

    }

    public abstract void receive(Event event);

}

Then I created Update

public class DocumentUpdate extends DocumentListener
{
    // injected constructor

    @Override
    public void receive(Event event)
    {
    }
}

And

public class DocumentDelete extends DocumentListener
{
    // injected constructor

    @Override
    public void receive(Event event)
    {
    }
}

Then Guice will complain with 1) [Guice/MissingImplementation]: because now the DocumentListener is an abstract class which it doesn't know how to bind.

I could do something like this

bind(DocumentListener.class).to(DocumentUpdate.class).in(SINGLETON);

But then I can only bind one class at a time. I can't bind two implementations as Guice will complain that the class is already binded and I can't bind twice.

Not sure if there's a pattern to solve this kind of problem with Guice and Listener pattern?

Aucun commentaire:

Enregistrer un commentaire