2011-01-04 4 views
0

WCF 서비스를 사용하는 프로젝트를 인수했습니다. 코드에는 몇 가지 "코드 냄새"가 있으며이 냄새를 리펙토링하고 싶습니다. 코드 중복 냄새를 리팩토링하는 방법에 대한 조언이 필요합니다. WCF 서비스에 의해 호출 될 때마다 방법은 다음과 같습니다() try {} catch {}

public Result MyMethod(string aString, string bString) 
{ 
    string methodName = MethodBase.GetCurrentMethod().Name; 
    using (LogService log = LogFactory.Create()) 
    { 
     try 
     { 
      <stmts> 
      log.Info(methodName, "Created entity xyz"); 
      <stmts> 
     } 
     catch (Exception ex) 
     { 
      log.Error(methodName, ex.message); 
     } 

    } 
} 

질문이 코드를 리팩토링 어떻게입니까? 모든 WCF 호출은이 "코드 템플릿"을 사용합니다.

답변

4

fol 전 (before)와 lowing 및 작업 후 : 예를 들어

private static void ActionWithLog(Action before, Action after) 
    { 
     string methodName = MethodBase.GetCurrentMethod().Name; 
     using (LogService log = LogFactory.Create()) 
     { 
      try 
      { 
       before(); 
       log.Info(methodName, "Created entity xyz"); 
       after(); 
      } 
      catch (Exception ex) 
      { 
       log.Error(methodName, ex.message); 
      } 
     } 
    } 

:

ActionWithLog(() => service.Operation1(),() => service.Operation2()); 
+0

내가 생각하고있는 점에서 뭔가가있었습니다. 감사! – Drazar

2

예외에 대한 좋은 점 중 하나는 잡히지 않으면 거품이 난다는 것입니다. 그래서 그들에게 레벨 (또는 몇 가지)을 붙잡 으면 큰 시도 잡기와 로깅이 도움이 될 것입니다. 예외의 .stacktrace 속성에는 메서드 이름이 포함되어 있습니다. 메시지 및 메서드 이름 대신 해당 정보를 잃어 버리지 않도록 로그하는 것이 매우 편리 할 것입니다.

당신은 위임 또는 액션/람다 식으로 내부 코드를 통과,이 코드 방법을 확인하고 호출 할 수 있습니다
2

: 좋아 다음

public Result MyMethod(string aString, string bString, MyDelegate a, MyDelegate b) 
{ 
    string methodName = MethodBase.GetCurrentMethod().Name; 
    using (LogService log = LogFactory.Create()) 
    { 
     try 
     { 
      a(); 
      log.Info(methodName, "Created entity xyz"); 
      b(); 
     } 
     catch (Exception ex) 
     { 
      log.Error(methodName, ex.message); 
     } 

    } 
} 

호출 :

MyMethod("foo", "bar", delegate{/*your code goes here*/}, delegate{/*your code goes here*/}); 

을 그렇게하지 않으면 인라인 대리자와 같이 별도의 메서드에서 대리자를 만들려면 다음과 같이하십시오.

MyMethod("foo", "bar", new MyDelegate(myMethodA), new MyDelegate(myMethodB)); 
0

그것은이다 같은 크로스 커팅 기능 : 당신은 그것을 제거하기 위해 AOP를 사용할 수있다 등 로깅, 예외 처리,. 그렇지 않으면이 코드를 리 팩터로 사용하지 않는 것이 좋습니다. .NET 용 AOP 프레임 워크는 다음과 같습니다. http://www.sharpcrafters.com/하지만 무료는 아닙니다. :) 무료로 검색 할 수 있습니다.

관련 문제