2 回答
TA贡献1820条经验 获得超10个赞
using System;
using System.Collections.Generic;
using System.Linq;
class Test
{
private object classmates;
public PersonResponse Add(PersonInsertRequest item)
{
var controller = new PersonController(classmates);
return ValidateAndExecute(() => controller.ValidateInsert(item),
() => controller.ExecuteInsert(item));
}
public PersonResponse Update(PersonUpdateRequest item)
{
var controller = new PersonController(classmates);
return ValidateAndExecute(() => controller.ValidateUpdate(item),
() => controller.ExecuteUpdate(item));
}
private PersonResponse ValidateAndExecute(Func<IEnumerable<string>> validator,
Func<PersonResponse> execute)
{
var result = new PersonResponse();
result.Messages = validator();
if (result.Messages != null && result.Messages.Any())
{
result.Status = "failed";
}
else
{
result = execute();
}
return result;
}
}
TA贡献1811条经验 获得超6个赞
通过基类中的通用方法,我可以重构我的方法
/// <summary>
/// Method Add with similar code in Update method
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public PersonResponse Add(PersonInsertRequest item)
{
var controller = new PersonController(classmates);
Validator myValidator = request => controller.ValidateInsert((PersonInsertRequest)request);
Executor myExecutor = request => controller.ExecuteInsert((PersonInsertRequest)request);
var result = Execute(item, myValidator, myExecutor);
return result as PersonResponse;
}
/// <summary>
/// Method Update with similar code in Add method
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public PersonResponse Update(PersonUpdateRequest item)
{
var controller = new PersonController(classmates);
Validator myValidator = request => controller.ValidateUpdate((PersonUpdateRequest)request);
Executor myExecutor = request => controller.ExecuteUpdate((PersonUpdateRequest)request);
var result = Execute(item, myValidator, myExecutor);
return result as PersonResponse;
}
- 2 回答
- 0 关注
- 92 浏览
添加回答
举报