samedi 25 juillet 2020

removing duplicate code shared between sync and async implementations

Given that I have an Processor interface:

public interface Processor {
    PBResponse process(PBEntity pbEntity);
}

And I have two implementation in my framework project, one synchronous:

@Service("Synchronous")
public class SyncProcessor implements Processor {

    private final PBRepository pbRepository;
    private final JobRunner jobRunner;

    public SyncProcessor(PBRepository pbRepository, JobRunner jobRunner) {
        this.pbRepository = pbRepository;
        this.jobRunner = jobRunner;
    }

    @Override
    public PBResponse process(PBEntity pbEntity) {
       pbRepository.save(pbEntity);
       //other business logic and run job
        jobRunner.runJob(pbEntity);
    }
}

The Other Async:

public class AsyncProcessor implements Processor {

    private final PBRepository pbRepository;
    private final JobRunner jobRunner;

    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    public SyncProcessor(PBRepository pbRepository, JobRunner jobRunner) {
        this.pbRepository = pbRepository;
        this.jobRunner = jobRunner;
    }

    @Override
    public PBResponse process(PBEntity pbEntity) {
        pbRepository.save(pbEntity);
        executorService.execute(new PBJobRunTask(pbRepository, jobRunner, pbEntity));
        return new PBResponse(...) //initial incomplete Response
    }

    private class PBJobRunTask implements Runnable {
        private final PBSFeedRepository pbsFeedRepository;
        private final JobRunner jobRunner;
        private final PBEntity pbEntity;

        public PBJobRunTask(PBRepository pbRepository, JobRunner jobRunner, PBEntity pbEntity) {
            //initialise
        }

        @Override
        public void run() {
            //other business logic and run job
            jobRunner.runJob(pbEntity);
        }
    }
}

Processing of a request is identical between both sync and async implementations. The only difference is the logic is executed with an ExecutorService with async implementation.

The processing logic is repeated in both Synchronous and Asynchronous implementations within the Runnable run() method:

   //duplicated
   pbRepository.save(pbEntity);
        //other business logic and run job
        jobRunner.runJob(pbEntity);

I need some help remove this duplicated where both these implementation can share. I am not sure whether inject Synchronous class into Async in a good practice as they are both implementations of Processor.

What would be ideal and a good pattern to share the business logic between two classes. We have the repository and JobRunner which also sits in both implementations and perhaps they can move also?

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire