2011-11-01 84 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(); 
}