태터데스크 관리자

도움말
닫기
적용하기   첫페이지 만들기

태터데스크 메시지

저장하였습니다.

language/java2008/01/28 15:25

Anti Pattern 이란 나쁜 코딩 패턴으로써 코딩시에 피해야 할 코딩 패턴들을 의미한다.

 

Exception-Handling Antipatterns

 

기본적인 exception 개념

  • Checked exception
    메소드의 throws 절에 선언되는 exception 이다.
    Exception 클래스를 확장한다.
    통상적인 시스템 이용 중에 발생할 수 있는 예상되는 문제를 나타낸다.
  • Unchecked exception
    throws 절에 선언될 필요는 없다.
    RuntimeException 클래스를 확장한다.
    예상치 못한 문제를 나타낸다. (대개의 원인은 버그 때문)
  • Error

Anti Patterns

  • Log and Throw
    catch (NoSuchMethodException e) {
          LOG.error("Blah", e);
          throw e;
    }
       
    or
       
    catch (NoSuchMethodException e) {
          LOG.error("Blah", e);
          throw new MyServiceException("Blah", e);
    }
       
    or
       
    cahch (NoSuchMethodException e) {
          e.printStachTrace();
          throw new MyServiceException("Blah", e);
    }
       
    Exception 로그를 작성하던지 exception을 던지던지 둘 중의 하나만 처리를 하라.
    두 개를 동시에 처리하면 하나의 문제에 대해서 여러개의 로그가 발생할 수 있으므로 디버깅이 어려울 수 있다.


  • Throwing Exception
    public void foo() throws Exception {
       
    checked exception 사용 목적에 전혀 맞지 않는 처리 방식이다.
    이것은 메서드에 뭔가가 잘못 되었다 라는 사실 밖에는 표현할 수 없다.
    메서드에서 throw 할 수 있는 특정한 checked exception 을 선언하라.

    이러한 exception 이 여러개라면 커스텀 exception 에 그것들을 wrap 하여야 한다.


  • Throwing the Kitchen Sink
    public void foo() throws MyException, AnotherException, SomeOtherException, YetAnotherException {


  • Catching Exception
    try {
          foo();
    } catch (Exception e) {
          LOG.error("Foo failed", e);
    }
       
    throw 될 수 있는 특정한 exception 을 catch 하라.
    Exception 클래스를 catch 하는 것의 문제점은
    현재 호출하고 있는 메서드에 새로운 checked exception 이 추가되었을 때 그 사실을 알지 못한다는 것이다.

    새로운 checked exception 의 추가에서 개발자의 의도는 추가된 exception 을 처리해야 하는 것이다.

       
  • Destructive Wrapping
    catch (NoSuchMethodException e) {
          throw new MyServiceException("Blah: " + e.getMessage());
    }
       
    이러한 방식은 원래의 exception의 stack trace를 파괴한다.

       
     
  • Log and Return Null
    catch (NoSuchMethodException e) {
          LOG.error("Blah", e);
          return null;
    }
       
    or
       
    catch (NoSuchMethodException e) {
          e.printStackTrace();
          return null;
    }
       
    항상 잘못된 것은 아니지만 대개는 잘못되었다.
    null 을 리턴하는 대신에 exception 을 던지고 호출자에게 그것을 처리하도록 하라.
    오직 정상적인 사용인 경우에만 null 을 리턴해야 한다. (예, "This method returns null if the search string was not found.")

       
     
  • Catch and Ignore
    catch (NoSuchMethodException e) {
          return null;
    }
       
    이것은 완전히 exception 을 삼켜버리고, 영원히 excetion 정보를 잃는다.
       

  • Throw from Within Finally
    try {
          blah();
    } finally {
          cleanUp();
    }
       
    이것은 cleanUp() 이 exception 을 절대 던지지 않을 경우에만 좋다.
    만약 blah() 가 exception 을 던지고 finally 절에서 cleanUp() 이 exception 을 던진다.
    그러면 두번째 exception 은 던져질 것이고 첫번째 exception 은 영원히 읽어버릴 것이다.
    finally 절에서 호출하는 코드가 exception 을 던질 가능성이 있으면 첫번째 exception 을 처리하든지 로그를 남겨야 한다.
       

  • Multi-Line Log Messages
    LOG.debug("Using cache policy A");
    LOG.debug("Using retry policy B");
       
    테스트 단계에서 여러번 log.debug() 를 호출하여 여러 라인의 로그 메세지를 사용하는 것은 괜찮아 보일 수 있다.
    하지만 병렬로 500개의 스레드를 실행중인 어플리케이션 서버의 로그파일에 보여질 때는,
    같은 로그 파일에 모든 정보들이 기록되고있고, 그러면 위 두개의 로그 메세지는 로그 파일에서 1000라인 이상 떨어져 나타날 수 있다.

       

  • Unsupported Operation Returning Null
    public String foo() {
          // Not supported in this implementation.
         return null;
    }
       
    추상 클래스를 구현할 때 선택적으로(optionally) 오버라이드하는 서브클래스를 위한 후크를 제공하는 것이면은 괜찮다.
    그러나 이 경우가 아니라면 null을 리턴하는 대신에 UnsupportedOperationException 을 던져야 한다.
    이러한 방식은 호출자에서 왜 동작하지 않는지를 훨씬 더 명확하게 알 수있게 만든다.

       

  • Ignoring InterruptedException
    while (true) {
          try {
            Thread.sleep(100000);
    } catch (InterruptedException e) {}
          doSomethingCool();
    }
       

  • Relying on getCause()
    catch (MyException e) {
          if (e.getCause() instanceof FooException) {
            ...
       

from http://today.java.net/pub/a/today/2006/04/06/exception-handling-antipatterns.html

'language > java' 카테고리의 다른 글

[eclipse] eclipse europa j2ee 실행 안될때,  (0) 2008/06/02
[Java] iBATIS 란?  (3) 2008/06/02
Anti Pattern  (0) 2008/01/28
UTF-8 Web Application 개발에 관한 정리  (0) 2008/01/28
Simple Java toolkit for JSON  (0) 2008/01/26
추상화, 인터페이스 개념 탑재  (0) 2008/01/07
Posted by THLIFE.net

TRACKBACK http://thlife.net/trackback/68 관련글 쓰기

댓글을 달아 주세요