Are there any reasons why you wouldn't use Code Contracts to enforce business rules?
Imagine you have a User
class that represents a single user of a system and defines actions that can be performed against other users. You could write a ChangePassword
method like this...
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.
...
}
Or you could implement the security check as a precondition with 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.
...
}
What are the advantages and disadvantages of these two methods?