【发布时间】:2018-09-27 13:46:13
【问题描述】:
我在 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)));
【问题讨论】:
-
将查询作为参数传递给您的函数
-
@Codeer 我同意你的看法,但只有在用户未提供值的情况下才可以接受(仍然不推荐)。
-
@killjoy 绝对正确。我暂时忘记了这一点
标签: java oop design-patterns code-reuse