Pergunta

I've seen this code pattern a few times over the years. Its the process of continually checking for a certain criteria where, if met, the method exits early. Is there a way to refactor this code to remove some of the redundant checks so that you don't have to continuously check the response from each supporting method?

For example:

public String process(String s) {
    String revised = doActionA(s);
    if (checkCriteria(revised)) return revised;

    revised = doActionB(revised);
    if (checkCriteria(revised)) return revised;

    return doActionC(revised);
}
Foi útil?

Solução

I think what you want here is the Chain of responsibility - Pattern. You'll need an 'Function': String -> String and a List, that contains those Functions. An evaluator will call each one of these and in the case of success, it will not call the remainding one - which is what you have in your example as well.

The term 'Function' could be anything from Java 8 Function Interface, Google Guava Function Interface or just a specialized functional interface like

public interface {
  String doAction(String parameterS);
}

You'll need to configure the evaluator before you use it with the 'Functions' / 'Actions' it should try. That could be as easy as adding them to the list, but you might want to extract that to a separate class as well.

If you want some examples, I think Google will provide you with plenty of them.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top