이 메서드는 컨텍스트의 핵심적인 내용을 잘 담고 있다
try/catch/finally
구분의 중첩 및 반복 → 가독성 저하로 코드 반환 부분을 잊기 쉬움 → 언젠가는 리소스 고갈 에러 발생
개방폐쇄 원칙 OCP : 많은 곳에서 중복되는 코드와 로직에 따라 자꾸 확장되고 자주 변화는 코드를 잘 분리해야 한다.
public void deleteAll() throws SQLException {
Connection c = null;
PreparedStatement ps = null;
try {
c = dataSource.getConnection();
// 유일하게 변하는 코드라인
ps = c.prepareStatement("delete from users");
ps.executeUpdate();
} catch (SQLException e) {
throw e;
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
}
}
if (c != null){
try{
c.close();
} catch (SQLException e){
}
}
}
}
변하는 부분: ps = c.prepareStatement("delete from users");
변하지 않는 부분: 그 외
변하는 부분을 메서드로 빼보자.
public void deleteAll() throws SQLException {
...
ps = makeStatement(c);
...
}
private PreparedStatement makeStatement(Connection c) throws SQLException{
PreparedStatement ps;
ps = c.prepareStatement("delete from users");
return ps;
}