이 메서드는 컨텍스트의 핵심적인 내용을 잘 담고 있다

JDBC try/catch/finally 코드의 문제점

try/catch/finally 구분의 중첩 및 반복 → 가독성 저하로 코드 반환 부분을 잊기 쉬움 → 언젠가는 리소스 고갈 에러 발생

개방폐쇄 원칙 OCP : 많은 곳에서 중복되는 코드와 로직에 따라 자꾸 확장되고 자주 변화는 코드를 잘 분리해야 한다.

3.2.2 분리와 재사용을 위한 디자인 패턴 적용

개선을 위해 가장 먼저 할 일

  1. 변화의 성격이 다른 것을 찾는다.
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");

변하지 않는 부분: 그 외

재사용하기 1. 메서드 추출

변하는 부분을 메서드로 빼보자.

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;
}
  1. 변하는 부분은 메서드로 추출
  2. 변하지 않는 부분에서 호출하도록

재사용하기 2. 템플릿 메서드 패턴의 적용