Reputation: 51
I apologize if I didn't ask the question correctly in advance.
I have about 15 related classes using the same code but different return types. How would I abstract that out to avoid code duplication in all these classes?
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;
}
and so on..
Upvotes: 0
Views: 68
Reputation: 7402
If the XXXResponse
types share a common super-type (class or interface), you can even solve it without generics, similar to @dubilyer's solution. (And for the love of future generations of programmers, do something about that silly catch
-block ;-)
Upvotes: 0
Reputation: 1013
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;
}
Do the same with parseQueryResults. Then move those methods to parent class.
Upvotes: 2