2014-03-28 2 views
1

두 가지 다른 서비스에서 두 가지 다른 메서드를 호출하는 함수를 작성했습니다. service1에 대한 작업을 수행하는 메소드를 호출하고 해당 호출이 성공하면 (예외가 발생하지 않음) service2를 호출하는 메소드를 호출합니다.두 개의 연속 부작용 메서드를 scala로 호출

def action1(param1: String, param2: String): Option[String] = { 
    try{ 
    //Check if service1 contains param1 
    getResultsFromService1(param1) match { 
    //If service1 doesn't contain param1 
    case None => { 
     //Perform action to insert param1 in service 1 
     performActionOnService1(param1) 
     //Upon successful completion of the previous function 
     //insert param1 and param2 in service2 
     performActionOnService2(param1,param2) 
     //Assuming both the actions completed successfully return Some(param1) 
     //indicating, the action was successfully performed 
     Some(param1) 
    } 
    //Service1 contains param1 
    case _ => { 
     //Check if service2 contains params 1 and 2 
     getResultsFromService2(param1,param2) match { 
     //Service2 doesn't contain param1 and param2, insert param1 and param2 
     //in service1 and return Some(param1) indicating that the action was 
     //successfully performed 
     case None => performActionOnService2(param1,param2);Some(param1) 
     //Service 2 contains params 1 and 2, return None indicating no action was performed 
     case _ => None 
     } 
    } 
    } 

    }catch{ 
    case ex:Throwable => throw ex;None 
    } 
} 

나는 이러한 기능을 구성하고 방법의 정확성과 함께 내 조각의 상세에 대한 걱정 다음과 같이

내 코드입니다. 누군가 내가 여기서 잘못하고있는 것을 지적 할 수 있습니까?

감사합니다.

+0

컴파일됩니까? 'case ex : Throwable => throw ex; None', None에 도달 할 수 없습니다. –

+0

분기가 값을 반환하므로 던지기의 부작용으로 컴파일됩니다 –

+0

왜 모든 것을 잡기 만하면됩니다. –

답변

2

리팩토링에서의 첫 걸음은 보유하고있는 유형 시스템을 포용하는 것입니다. 당신은 어떤 일을했을 때 또는하지 않을 때 어떤 행동을 취하는 것처럼 보입니다 : Option[String], 그러나 역시 try ... catch throw을 실패 할 수 있습니다.

첫 번째 단계는 Try[Option[String]]으로 작업하고 웹 서비스로 처리 할 가능성이 가장 높으므로 결국 실패 할 수있는 무언가를 수행하는 것으로 변환되는 Future[Option[String]]으로 끝납니다.

그리고 당신이 그와 함께 할 때, 당신은 당신이 당신의 프로그램이 코멘트에 남아있는 경우에 대처하기 위해, 더 나은 흐름을 재구성 할 필요가 있음을 알 수 있습니다 (예를 들어 Upon successful completion...) 그 Future

모든 3, TryOption은 결과의 모나드 구성에 mapflatMap을 사용할 수 있습니다.

관련 문제