【发布时间】:2011-01-01 05:15:01
【问题描述】:
我很难确定一个好的标题,因此如有必要,请随时更改。我不太确定如何描述我想要实现的目标,我想到了“模板”这个词(显然我不是在尝试使用 C++ 模板)。
如果我有一个类在每个方法中执行一些操作,让我们假装做一个 try/catch 和其他一些东西:
public class SomeService
{
public bool Create(Entity entity)
{
try
{
this.repository.Add(entity);
this.repository.Save();
return true;
}
catch (Exception e)
{
return false;
}
}
}
然后我添加另一个方法:
public bool Delete(Entity entity)
{
try
{
this.repository.Remove(entity);
this.repository.Save();
return true;
}
catch (Exception e)
{
return false;
}
}
这里的方法显然有一个模式:try/catch 与返回值。所以我在想,既然服务上的所有方法都需要实现这种工作模式,我是否可以将它重构为这样的东西:
public class SomeService
{
public bool Delete(Entity entity)
{
return this.ServiceRequest(() =>
{
this.repository.Remove(entity);
this.repository.Save();
});
}
public bool Create(Entity entity)
{
return this.ServiceRequest(() =>
{
this.repository.Add(entity);
this.repository.Save();
});
}
protected bool ServiceRequest(Action action)
{
try
{
action();
return true;
}
catch (Exception e)
{
return false;
}
}
}
这样,所有方法都遵循相同的“模板”执行。这是一个糟糕的设计吗?请记住,try/catch 并不是每种方法都可能发生的。考虑添加验证,每个方法都需要说if(!this.Validate(entity))...。
这是否太难维护/丑陋/糟糕的设计?
【问题讨论】:
-
您确定要阻止异常执行其工作吗?
-
@Dialectus - 请参阅我今天之前的帖子,了解应该从服务方法返回的值:stackoverflow.com/questions/4570717/… 请记住,这只是一个示例,它可能是其他一些方法“模板”。
标签: c#