Java代码在两个或多个具有相同代码的方法中重用

时间:2018-04-17 14:24:25

标签: java oop design-patterns code-reuse

我在Java中使用以下代码来查询数据库:

public interface MapReduceDAO {

    String host = "mysql";
    int port = 3306;
    String user = "root";
    String password = "root";
    String dbName = "customers";

    default String customersMysqlUrl(String name) {
        return getDocker().containers().container(name).port(port).inFormat("$HOST:$EXTERNAL_PORT");
    }

    default void checkTableHasData(Duration atMost, String tableName) throws Exception {
        try (MysqlQuery mysqlQuery = new MysqlQuery(customersMysqlUrl(host), dbName, user, password)) {

            await().atMost(atMost).pollDelay(Duration.ONE_SECOND).ignoreExceptions().until(
            () -> mysqlQuery.count("SELECT COUNT(*) FROM " + tableName),
            is(Matchers.greaterThan(0)));
        }
    }

    default void checkExistsQuery(Duration atMost, String tableName, int countValueExpected) throws Exception {
    try (MysqlQuery mysqlQuery = new MysqlQuery(customersMysqlUrl(host), dbName, user, password)) {

        await().atMost(atMost).pollDelay(Duration.ONE_SECOND).ignoreExceptions().until(
        () -> mysqlQuery.count("SELECT COUNT(*) FROM " + tableName),
        is(Matchers.equalTo(countValueExpected)));
    }
}

    DockerComposeRule getDocker();
}

如何避免使用重复的代码。在方法checkTableHasData和checkExistsQuery中,我大多重复代码。

编辑:忘记提及,他们最后可能有不同的断言,例如:

  

是(Matchers.greaterThan(0)));

     

是(Matchers.equalTo(countValueExpected)));

2 个答案:

答案 0 :(得分:2)

如果我看到的正确,那么这些方法只会与您提供给count()的参数不同。只需引入一个方法,将其作为参数并使用不同的值调用它。

default void checkTableHasData(Duration atMost, String tableName) throws Exception {
    check(atMost, "SELECT COUNT(*) FROM " + tableName);
}

default void checkTableRowExistSearchOnColumn(Duration atMost, String tableName, String columnName,
                                              String columnValue) throws Exception {
    check(atMost, "SELECT COUNT(*) FROM " + tableName + " where " + columnName +
                               " = " + columnValue);
}

private void check(Duration atMost, String countStatement) throws Exception {
    try (MysqlQuery mysqlQuery = new MysqlQuery(customersMysqlUrl(host), dbName, user, password)) {

        await().atMost(atMost).pollDelay(Duration.ONE_SECOND).ignoreExceptions().until(
        () -> mysqlQuery.count(countStatement),
        is(Matchers.greaterThan(0)));
    }
}

答案 1 :(得分:1)

您可以使用单独的方法简单地提取常见行为:

inRange