0

WCF WebApiプレビュー5を使用してWebAPIを開発しています。現在、リソースクラスは完全に機能していますが、このリソース内のメソッドが複雑になっていることに気づきました。

例えば:

[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);
        }
    }

お気づきかもしれませんが、このメソッドには新しい物理テストを投稿するタスクがありますが、実際にはモデルも検証しています(まだ多くの検証、プロパティ検証が欠落しています)。これはこのクラスの問題ではありません。リソース内のメソッドの複雑さを軽減するための親しみやすい方法はありますか?

4

1 に答える 1

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();
}
于 2011-11-01T20:15:42.593 に答える