除了内部的方法调用和返回类型之外,我有两个非常相似的方法。我想知道是否有办法使它更整洁,即不重复锅炉板连接代码。我考虑在方法签名中添加一个标志来切换,类似于isMultiple,但最后我不喜欢这样,因为返回类型不同,不能工作。我想知道我是否可以用Java 8做什么好事。
方法:
protected String getSingleFilePathResult(Query query) throws UwsException {
JdbcPooledConnection conn = createConnection();
try {
return conn.getSingleFilePathResult(query);
} catch (SQLException sqle) {
throw new UwsException(SQL_EXCEPTION + sqle.getMessage(), sqle);
} finally {
closeConnection(conn);
}
}
protected List<String> getMultipleFilePathResults(Query query) throws UwsException {
JdbcPooledConnection conn = createConnection();
try {
return conn.getMultipleFilePathResults(query);
} catch (SQLException sqle) {
throw new UwsException(SQL_EXCEPTION + sqle.getMessage(), sqle);
} finally {
closeConnection(conn);
}
}发布于 2017-08-03 11:23:57
你可以像这样把样板分出来:
protected String getSingleFilePathResult(Query query) throws UwsException {
return doWithConnection(conn -> conn.getSingleFilePathResult(query));
}
protected List<String> getMultipleFilePathResults(Query query) throws UwsException {
return doWithConnection(conn -> conn.getMultipleFilePathResults(query));
}
protected <T> T doWithConnection(Function<conn, T> callback) throws UwsException {
try (JdbcPooledConnection conn = createConnection()){
return callback.Invoke(conn);
} catch (SQLException sqle) {
throw new UwsException(SQL_EXCEPTION + sqle.getMessage(), sqle);
}
}发布于 2017-08-03 09:38:32
正如Mario已经写过的,在不增加复杂性的情况下,很难减少代码的重复,例如,您可以这样做:
interface PathResult {
List<String> getResult(JdbcPooledConnection conn, Query query) throws SQLException;
}
class MultiplePathResult implements PathResult {
@Override
public List<String> getResult(JdbcPooledConnection conn, Query query) throws SQLException {
return conn.getMultipleFilePathResults(query);
}
}
class SinglePathResult implements PathResult {
@Override
public List<String> getResult(JdbcPooledConnection conn, Query query) throws SQLException {
return conn.getSingleFilePathResult(query);
}
}然后将有一个方法getPathResults(查询,PathResult pathResult)。
protected List<String> getPathResults(Query query, PathResult pathResult) throws UwsException {
JdbcPooledConnection conn = createConnection();
try {
return pathResult.getResult(conn, query);
} catch (SQLException sqle) {
throw new UwsException(SQL_EXCEPTION + sqle.getMessage(), sqle);
} finally {
closeConnection(conn);
}
}发布于 2017-08-03 09:24:26
我认为你的代码是非常清晰和直接的。这是一件好事,对谁都要读懂它。
如果没有更多的上下文,我就可以假设您的类是数据库的包装器,并且在代码中使用它来执行查询,从而避免数据库依赖。
我认为,在不增加他的复杂性和可读性的情况下,减少代码的复制是相当困难的。
您可以牺牲一点内存,但是将getMultipleFilePathResults(查询)封装在getSingleFilePathResult(查询)中,如下所示:
protected String getSingleFilePathResult(Query query) throws UwsException {
List<String> result = getMultipleFilePathResults(Query query);
if (result.size() == 1) {
return result.get(0);
} else {
// have to handle this...
}
}但是,正如您所看到的,事情并不是那么清楚,因为现在您使用大量内存来分配列表,并且需要处理一个新的案例。
https://codereview.stackexchange.com/questions/171951
复制相似问题