我們與同事討論了流量控制模式和通用代碼設計。需要您的意見 - 哪種編寫代碼更好/更清潔/更受歡迎?流量控制模式和最佳實踐
這是爲MVC 3,但這並不重要。
版本1:
public ActionResult Login(LoginData loginData)
{
if (!ModelState.IsValid)
{
ShowGlobalError("Invalid credentials.");
return View(loginData);
}
UserProfile profile = null;
try
{
// see if we have profile with those credentials
profile = this.RetrieveUserProfile(loginData.Email.Trim(), loginData.Password.Trim()); // this just goes to db and tries to get user profile. Returns null if profile isn't found
}
catch (Exception ex)
{
ShowGlobalError("DB is down");
LogError(...);
return View(loginData);
}
if (profile == null)
{
// nope, we don't.. ask again
ShowGlobalError("Invalid credentials.");
return View(loginData);
}
// ok, we're good
Session["Profile"] = profile;
FormsAuthentication.SetAuthCookie(profile.Email, false);
FormsAuthentication.RedirectFromLoginPage(profile.Email, loginData.EnablePermanentCookie);
return View(loginData);
}
版本2:
public ActionResult Login(Credentials credentials){
try{
PersonalProfile profile = AuthenticateUser(credentials);
SetProfileSessionstate(profile); // this does 'Session["Profile"] = profile;'
SetFormsAuthenticationAndRedirect(profile);
}
catch(Exception ex){
ShowGlobalError("invalid login, please try again.");
}
return View(credentials);
}
public void SetFormsAuthenticationAndRedirect(PersonalProfile profile){
FormsAuthentication.SetAuthCookie(profile.Email, loginData.EnablePermanentCookie);
FormsAuthentication.RedirectFromLoginPage(profile.Email, loginData.EnablePermanentCookie);
}
1版充滿了return語句,第2版使用try/catch語句進行流量控制。 那麼,哪種方式更好,還是我們都做錯了,還有更好的方法可以分享?
謝謝!
所以第1版應該是相當於2個版本?因爲它看起來不像他們做同樣的事情。 – Phil 2011-03-10 14:34:40
是的,他們基本上是做同樣的事情 - 用戶登錄,如果個人資料已被實際檢索 – Evgeni 2011-03-10 14:39:44