Code Smell 80 - 중첩된 Try/Catch

예외는 행복한 길과 문제의 길을 구분하는 좋은 방법입니다. 그러나 우리는 솔루션을 지나치게 복잡하게 만드는 경향이 있습니다.

TL;DR: Don't nest Exceptions. Nobody cares of what you do in the inner blocks.



문제


  • 가독성

  • 솔루션


  • 리팩터링

  • 샘플 코드



    잘못된




    try {
        transaction.commit();
    } catch (e) {
        logerror(e);
        if (e instanceOf DBError){
          try {
              transaction.rollback();
          } catch (e) {
              doMoreLoggingRollbackFailed(e);
          }
        }
    }
    
    //Nested Try catchs
    //Exception cases are more important than happy path
    //We use exceptions as control flow
    

    오른쪽



    try {
        transaction.commit();
    } catch (transactionError) {
        this.withTransactionErrorDo(transationError, transaction);
    }
    
    //transaction error policy is not defined in this function
    //so we don't have repeated code
    //code is more readable
    //It is up to the transaction and the error to decide what to do
    

    발각



    구문 분석 트리를 사용하여 이 냄새를 감지할 수 있습니다.

    태그


  • 예외

  • 결론



    예외를 남용하지 말고 아무도 잡을 수 없는 예외 클래스를 만들지 말고 모든 경우에 대비하지 마십시오(커버링 테스트가 있는 좋은 실제 시나리오가 없는 한).

    항상 예외적인 경우보다 행복한 길이 더 중요해야 합니다.

    처지











    더 많은 정보


  • Nested Try/Catchs

  • 학점



    사진 제공: David Clode on Unsplash

    영감을 준 @에게 감사합니다.









    로드리고









    ✍️ Clean code tip try/catch추출 예외 처리 방식과 로직을 분리합니다. 여러 try/catch를 사용하면 코드의 의도가 흐려지므로 코드를 읽을 수 있도록 분리하는 것이 좋습니다.두 번째 그림에서 코드가 얼마나 개선되었는지 보세요.


    오후 14:32 - 2021년 6월 11일











    Writing software as if we are the only person that ever has to comprehend it is one of the biggest mistakes and false assumptions that can be made.



    카롤리나 슈추르






    이 기사는 CodeSmell 시리즈의 일부입니다.


    좋은 웹페이지 즐겨찾기