【发布时间】:2011-01-13 23:21:51
【问题描述】:
您有什么理由不使用代码合同来执行业务规则?
假设您有一个User 类,它代表系统的单个用户并定义可以针对其他用户执行的操作。您可以像这样编写ChangePassword 方法...
public void ChangePassword(User requestingUser, string newPassword)
{
Contract.Requires<ArgumentNullException>(requestingUser);
Contract.Requires<ArgumentNullException>(newPassword);
// Users can always change their own password, but they must be an
// administrator to change someone else's.
if (requestingUser.UserId != this.UserId &&
!requestingUser.IsInRole("Administrator"))
throw new SecurityException("You don't have permission to do that.");
// Change the password.
...
}
或者您可以使用Contract.Requires...作为前提条件实施安全检查...
public void ChangePassword(User requestingUser, string newPassword)
{
Contract.Requires<ArgumentNullException>(requestingUser != null);
Contract.Requires<ArgumentNullException>(newPassword != null);
// Users can always change their own password, but they must be an
// administrator to change someone else's.
Contract.Requires<SecurityException>(
requestingUser.UserId == this.UserId ||
!requestingUser.IsInRole("Administrator"),
"You don't have permission to do that.");
// Change the password.
...
}
这两种方法的优缺点是什么?
【问题讨论】:
标签: security .net-4.0 code-contracts