如何在多个类中抽象出具有不同返回类型的相同方法

时间:2019-08-06 05:11:58

标签: java class refactoring

如果事先没有正确提出问题,我深表歉意。

我有大约15个相关的类,它们使用相同的代码,但返回类型不同。我如何抽象出来以避免在所有这些类中重复代码?

    public ChargeResponse findByTransactionId(final String txId) {
        ChargeResponse chargeResponse = null;
        try (Connection connection = dataSource.getConnection()) {
            PreparedStatement preparedStatement = connection.prepareStatement(VIEW_SERVICE_TRANSACTION_CHARGE_QUERY);
            preparedStatement.setString(1, txId);
            final ResultSet resultSet = preparedStatement.executeQuery();
            chargeResponse = parseQueryResults(resultSet);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return chargeResponse;
    }
    public EventsResponse findByTransactionId(final String txId) {
        EventsResponse eventsResponse = null;
        try (Connection connection = dataSource.getConnection()) {
            PreparedStatement preparedStatement = connection.prepareStatement(VIEW_SERVICE_TRANSACTION_EVENTS_QUERY);
            preparedStatement.setString(1, txId);
            final ResultSet resultSet = preparedStatement.executeQuery();
            eventsResponse = parseQueryResults(resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return eventsResponse;
    }

以此类推。

2 个答案:

答案 0 :(得分:2)

public <T> T findByTransactionId(final String txId) {
    T chargeResponse;
    try (Connection connection = dataSource.getConnection()) {
        PreparedStatement preparedStatement = connection.prepareStatement(VIEW_SERVICE_TRANSACTION_CHARGE_QUERY);
        preparedStatement.setString(1, txId);
        final ResultSet resultSet = preparedStatement.executeQuery();
        chargeResponse = parseQueryResults(resultSet);

    } catch (SQLException e) {
        e.printStackTrace();
    }
    return chargeResponse;
}

对parseQueryResults执行相同的操作。然后将这些方法移到父类。

答案 1 :(得分:0)

如果XXXResponse类型共享一个公共的超类型(类或接口),您甚至可以在没有泛型的情况下解决它,类似于@dubilyer的解决方案。 (出于对子孙后代程序员的热爱,请对这个愚蠢的catch-block ;-)做些事情