static method만을 가지는 utility class는 private 생성자를 가지도록 구현한다.

2015-04-09 11:03

static method만을 가지는 utility class는 굳이 public 생성자를 가질 필요가 없다.

public class Forwarding {
    public static void doForward(HttpServletRequest req, HttpServletResponse resp, String errorKey,
            String errorMessage, String destination) throws ServletException, IOException {
        req.setAttribute(errorKey, errorMessage);
        RequestDispatcher rd = req.getRequestDispatcher(destination);
        resp.setStatus(500);
        rd.forward(req, resp);
    }


    public static void doForward(HttpServletRequest req, HttpServletResponse resp, String destination)
            throws ServletException, IOException {
        doForward(req, resp, "", "", destination);
    }


    public static void forwardForException(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        doForward(req, resp, "", "", "/exception.jsp");
    }
}

위 코드는 public 기본 생성자를 제공하지 않고 다음과 같이 private 생성자로 구현하는 것이 잘못된 사용을 방지할 수 있다.

public class Forwarding {
    private Forwarding() {}


    public static void doForward(HttpServletRequest req, HttpServletResponse resp, String errorKey,
            String errorMessage, String destination) throws ServletException, IOException {
        req.setAttribute(errorKey, errorMessage);
        RequestDispatcher rd = req.getRequestDispatcher(destination);
        resp.setStatus(500);
        rd.forward(req, resp);
    }


    public static void doForward(HttpServletRequest req, HttpServletResponse resp, String destination)
            throws ServletException, IOException {
        doForward(req, resp, "", "", destination);
    }


    public static void forwardForException(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        doForward(req, resp, "", "", "/exception.jsp");
    }
}

0개의 의견 from SLiPP

의견 추가하기

연관태그

← 목록으로