samedi 8 décembre 2018

Is the Chain of Responsibility pattern a good replacement for a sequence of conditions?

When you need to execute a sequence of actions in a particular order, is the Chain of Responsibility pattern a good replacement for a sequence of conditions? Is it a good idea to replace a simple method with conditions like this:

public class MyListener implements MyHttpListener {

    // if false, the request will be thrown away and subsequent listeners will not be notified
    @Override
    public boolean onHttpRequestSend(HttpMessage msg) { 
        // handlers can change msg

        boolean isA = handleA(msg);
        if (isA) return false;

        boolean isB_notA = handleB(msg);
        if (isB_notA) return false;

        boolean isC_notA_notB = handleC(msg);
        if (isC_notA_notB) return true;

        ...

        throw new IllegalStateException();
    }
}

Now replace it with an implementation of the Chain of Responsibility pattern:

public class MyListener implements MyHttpListener {
    @Override
    public boolean onHttpRequestSend(HttpMessage msg) {
        ProcessingStep first = new StepA()
        ProcessingResult result = first.process(new ProcessingResult(msg, true));
        return result.returnValue;
    }
}

public interface ProcessingStep {
    ProcessingResult process(ProcessingResult stepResult);
}

public class ProcessingResult {
    HttpMessage message;
    boolean returnValue;
}

public class StepA implements ProcessingStep {
    @Override
    public ProcessingResult process(ProcessingResult stepResult) {
        if (handleA()) {
            return stepResult;
        }
        else {
            return new StepB().process(stepResult);
        }
    }
}   
public class StepB implements ProcessingStep {
    @Override
    public ProcessingResult process(ProcessingResult stepResult) {
        return stepResult; // this is the last step
    }
}

Aucun commentaire:

Enregistrer un commentaire