gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:20:10 25 4
gpt4 key购买 nike

我在 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 中,我主要重复了代码。

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

is(Matchers.greaterThan(0)));

is(Matchers.equalTo(countValueExpected)));

最佳答案

如果我没看错的话,这些方法只是在你给 count() 的参数上有所不同。只需引入一个将 this 作为参数并使用不同值调用它的方法。

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)));
}
}

关于在具有相同代码的两个或多个方法中重用 Java 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49880699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com