2011-11-01 54 views
0

我正在開發一個使用WCF Web Api預覽版的web api 5.目前我有一個資源類功能齊全,我怎麼會注意到這個資源中的方法變得越來越複雜。減少服務類的複雜性

例如:

[WebInvoke(UriTemplate = "{EhrID}/PhysicalTest",Method="POST")] 
    public HttpResponseMessage<DTO.PhysicalTest> PostPhysicalTest(int EhrID, DTO.PhysicalTest PhysicalTestDTO) 
    { 
     var EHR = repository.FindById(EhrID); 
     var PhysicalTest = Mapper.Map<DTO.PhysicalTest, PhysicalTest>(PhysicalTestDTO); 

     if (PhysicalTest == null) 
     {     
      var response = CreateResponseForException("No object to store", HttpStatusCode.BadRequest); 
      throw new HttpResponseException(response); 
     } 

     try 
     { 
      if (EHR.PhysicalTests == null) 
      { 
       EHR.PhysicalTests = new List<PhysicalTest>(); 
      } 
      PhysicalTest.CreationDate = DateTime.Now; 
      EHR.PhysicalTests.Add(PhysicalTest); 
      _unitOfWork.Commit(); 
      return new HttpResponseMessage<DTO.PhysicalTest>(PhysicalTestDTO, HttpStatusCode.Created); 
     } 
     catch (Exception ex) {     
      var response = CreateResponseForException("Cannot create Physical Test", HttpStatusCode.InternalServerError); 
      throw new HttpResponseException(response); 
     } 
    } 

正如你可能會注意到這種方法有發佈了新的物理實驗的任務,但它實際上是驗證我的模型太(我失去了很多驗證的是,財產驗證) ,這不應該成爲這個階級關心的問題。如果有任何可行的方法來減少資源內部方法的複雜性?

+0

少於20行的函數並不複雜,但它看起來很複雜,因爲您使用了很多行來驗證PhysicalTest。此外,你用大寫字母拼寫變量名稱的事實使得很難區分類的類型和變量。 – Casperah

+0

但我在哪裏可以做這些驗證,所以我的資源方法看起來很簡單? – Daniel

回答

0

我會把它分成更小更集中的方法。我可能也會開始使用實例變量,而不是傳遞所有這些參數,但爲了這篇文章的緣故,我重寫了它,而沒有將東西推送到實例變量。

[WebInvoke(UriTemplate = "{EhrID}/PhysicalTest",Method="POST")] 
public HttpResponseMessage<DTO.PhysicalTest> PostPhysicalTest(int EhrID, DTO.PhysicalTest PhysicalTestDTO) 
{ 
    var EHR = repository.FindById(EhrID); 
    var PhysicalTest = Mapper.Map<DTO.PhysicalTest, PhysicalTest>(PhysicalTestDTO); 

    if (PhysicalTest == null) 
    {     
     var response = CreateResponseForException("No object to store", HttpStatusCode.BadRequest); 
     throw new HttpResponseException(response); 
    } 

    PostPhysicalTest(EHR, PhysicalTest); 
    return new HttpResponseMessage<DTO.PhysicalTest>(PhysicalTestDTO, HttpStatusCode.Created); 
} 

private void PostPhysicalTest(EHR ehr, PhysicalTest physicalTest) 
{ 
    try 
    { 
     CreatePhysicalTest(ehr, physicalTest); 
    } 
    catch (Exception ex) {     
     var response = CreateResponseForException("Cannot create Physical Test", HttpStatusCode.InternalServerError); 
     throw new HttpResponseException(response); 
    } 
} 

private void CreatePhysicalTest(EHR ehr, PhysicalTest physicalTest) 
{ 
    if (ehr.PhysicalTests == null) 
    { 
     ehr.PhysicalTests = new List<PhysicalTest>(); 
    } 

    physicalTest.CreationDate = DateTime.Now; 
    ehr.PhysicalTests.Add(physicalTest); 
    _unitOfWork.Commit(); 
}