比方說,我們有一個在MVC應用程序:拋出異常時,沒有指定的情況下,可以處理
public JsonResult ChangePassword
(string username, string currentPassword, string newPassword)
{
switch (this.membershipService.ValidateLogin(username, currentPassword))
{
case UserValidationResult.BasUsername:
case UserValidationResult.BadPassword:
// abort: return JsonResult with localized error message
// for invalid username/pass combo.
case UserValidationResult.TrialExpired
// abort: return JsonResult with localized error message
// that user cannot login because their trial period has expired
case UserValidationResult.Success:
break;
}
// NOW change password now that user is validated
}
membershipService.ValidateLogin()
返回UserValidationResult
枚舉改變了用戶的密碼系統中的一個函數,被定義爲:
enum UserValidationResult
{
BadUsername,
BadPassword,
TrialExpired,
Success
}
作爲一個防禦性的程序員,我會改變上述ChangePassword()
方法拋出一個異常,如果有一個無法識別的UserValidationResult
值從ValidateLogin()
回:
public JsonResult ChangePassword
(string username, string currentPassword, string newPassword)
{
switch (this.membershipService.ValidateLogin(username, currentPassword))
{
case UserValidationResult.BasUsername:
case UserValidationResult.BadPassword:
// abort: return JsonResult with localized error message
// for invalid username/pass combo.
case UserValidationResult.TrialExpired
// abort: return JsonResult with localized error message
// that user cannot login because their trial period has expired
case UserValidationResult.Success:
break;
default:
throw new NotImplementedException
("Unrecognized UserValidationResult value.");
// or NotSupportedException()
break;
}
// Change password now that user is validated
}
我一直認爲模式就像最後一個片段的最佳實踐。例如,如果一個開發人員現在要求用戶嘗試登錄時要求,如果出於這種或那種商業原因,他們是否會首先聯繫業務?所以UserValidationResult
的定義更新爲:
enum UserValidationResult
{
BadUsername,
BadPassword,
TrialExpired,
ContactUs,
Success
}
開發商改變了ValidateLogin()
方法的身體恢復新枚舉值(UserValidationResult.ContactUs
)適用的時候,卻忘記更新ChangePassword()
。在交換機中沒有例外的情況下,用戶仍然可以在他們的登錄嘗試甚至不需要首先驗證時更改密碼!
難道只是我,或者是這default: throw new Exception()
一個好主意嗎?我幾年前就看到了它,並且始終(在通過它之後)認爲這是最佳做法。
Oooh很好,以前沒見過這個Exception衍生物。謝謝:) – CantSleepAgain 2010-07-28 03:04:51
有趣的是,我希望它是在Visual Studio中創建一個新類時默認包含的名稱空間之一。 – Davy8 2010-07-28 03:10:35
只有當承受枚舉是一個參數時,它纔會在語義上正確。情況並非總是如此:http://stackoverflow.com/questions/13645149/what-is-the-correct-exception-to-throw-for-unhandled-enum-values – 2013-08-21 09:01:39