Created
August 31, 2010 09:12
-
-
Save anelson/558776 to your computer and use it in GitHub Desktop.
Don't Repeat Yourself, Kyiv 2010
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UserManager { | |
public bool IsLoggedIn { get; private set; } | |
public void LogIn(string userName, string password) { | |
if (IsLoggedIn) { | |
throw new InvalidOperationException("The user is already logged in"); | |
} | |
if (userName == _userName && password == _password) { | |
IsLoggedIn = true; | |
} else { | |
throw new ArgumentException("Invalid username or password"); | |
} | |
} | |
public void ChangePassword(string userName, string oldPassword, string newPassword) { | |
if (IsLoggedIn) { | |
throw new InvalidOperationException("The user is already logged in"); | |
} | |
if (userName == _userName && oldPassword == _password) { | |
_password = newPassword; | |
} else { | |
throw new ArgumentException("Invalid username or password"); | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UserManager { | |
public bool IsLoggedIn { get; private set; } | |
public void LogIn(string userName, string password) { | |
EnsureUserNotLoggedIn(); | |
VerifyCredentials(userName, password); | |
IsLoggedIn = true; | |
} | |
public void ChangePassword(string userName, string oldPassword, string newPassword) { | |
EnsureUserNotLoggedIn(); | |
VerifyCredentials(userName, oldPassword); | |
_password = newPassword; | |
} | |
private void EnsureUserNotLoggedIn() { | |
if (IsLoggedIn) { | |
throw new InvalidOperationException("The user is already logged in"); | |
} | |
} | |
private void VerifyCredentials(string userName, string password) { | |
if (userName != _userName || password != _password) { | |
throw new ArgumentException("Invalid username or password"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note how the same logic to check that a user is not already logged in, compare usernames and passwords, and throw certain exceptions is repeated in two places. We can clean this up to make the code more readable and less duplicative.