mardi 17 avril 2018

Java code reuse in two or more methods with same code

I have the following code in Java to query a database:

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 checkTableRowExistSearchOnColumn(Duration atMost, String tableName, String columnName,
                                                  String columnValue) 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 + " where " + columnName +
                                   " = " + columnValue),
            is(Matchers.greaterThan(0)));
        }
    }

    DockerComposeRule getDocker();
}

It may be a silly beginner question but how can I avoid using repeated code. In method checkTableHasData and checkTableRowExistSearchOnColumn, I have mostly repeated code. Can someone suggest a way to avoid this using current example and in code! Thank you!

Aucun commentaire:

Enregistrer un commentaire