在 ASP.net MVC(不一定限于 MVC,只是一个例子)中,我们的 action 方法中总是有前置条件,类似于下面的:
[HttpPost]
public ActionResult Edit(FooModel viewModel)
{
if (viewModel == null)
{
throw new ArugmentNullException("viewModel");
}
if (viewModel.Foo < 1)
{
throw new InvalidOperationException();
}
// Perform real tasks on viewModel (e.g. map it to model, persist to database)
}
现在我知道我们可以将检查重构为存储库类中的静态方法:
[HttpPost]
public ActionResult Edit(FooModel viewModel)
{
if (FooModelRepostory.IsValid(viewModel)
{
}
// Perform real tasks
}
在FooModelRepository.cs
:
public static bool IsValid(FooModel viewModel)
{
if (viewModel == null)
{
throw new ArgumentNullException("viewModel");
}
if (viewModel.Foo < 1)
{
throw new InvalidOperationException();
}
// ...many more checks and throw exceptions accordingly
// if we reach up to here, we are good, return true
return true;
}
我的问题是,我们有没有更好的方法来重构代码,而不用像这样的检查使存储库混乱?