Skip to content

Instantly share code, notes, and snippets.

@anelson
Created August 31, 2010 09:12
Show Gist options
  • Save anelson/558776 to your computer and use it in GitHub Desktop.
Save anelson/558776 to your computer and use it in GitHub Desktop.
Don't Repeat Yourself, Kyiv 2010
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");
}
}
}
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");
}
}
}
@anelson
Copy link
Author

anelson commented Aug 31, 2010

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment