Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I use a chain of responsibility over a switch-statement

Consider you got several validations. Those validations should only take effect if the object to be inspected is of a certain type. Why would I use a chain of responsibility over a switch-statement?

Example with chain of responsibility

public class Executor {

@Inject
private ValidatorFactory validatorFactory;

public void execute(Konfiguration konfig) {
    List<Statement> statements = konfig.getStatements();
    AbstractValidator validator = validatorFactory.create();
    for (Statement statement : statements) {
        if (validator.validate(statement.getType())) {
            crudService.execute(statement.getSql());
        }
    }
}

The validatorFactory creates the chain of Validators. One validator would look like

public class AddPrimaryKeyValidator extends AbstractValidator {

@Override
public boolean validate(Statement statement) {
    if (SqlType.ADD_PK.getTyp().equals(statement.getType())) {
        return doesTableAndPrimaryKeyExist(statement.getTabName());
    }
    return successor.validate(statement);
}

Example with switch-statement

public void execute(Konfiguration konfig) {
    List<Statement> statements = konfig.getStatements();
    for (Statement statement : statements) {
        switch (statement.getType()) {
        case "ADD_PK":
            if (doesTableAndPrimaryKeyExist(statement.getTabName())) {
                frepCrudService.execute(statement.getSql());
            }
            // more cases
        }
    }
}
like image 398
Chris311 Avatar asked Oct 19 '15 14:10

Chris311


1 Answers

Because in a chain of responsibility you don't need to know who does what up front in the caller. The logic of decide when you are about to run your piece of code in a chain is owned by you and the rest of the code can ignore it. This allow to encapsulate specific logic in the right place. Servlet filters are a good example of this

like image 127
Filippo Fratoni Avatar answered Oct 16 '22 06:10

Filippo Fratoni