Consider the following code:
public class User {
private String password;
public void changePassword( String oldPassword,
String newPassword) throws WrongOldPasswordException,
NewPasswordTooWeakException
{
if (password != null) {
if (!password.equals(oldPassword)) {
throw new WrongOldPasswordException();
}
}
if (newPassword.length() < 4)
throw new NewPasswordTooWeakException();
this.password = newPassword;
}
public static class WrongOldPasswordException extends Exception {
}
public static class NewPasswordTooWeakException extends Exception {
}
}
With the current API design, my presentation layer knows exactly what to do:
class UserViewController {
User user;
void changePassword() {
String oldPassword = view.getOldPassword();
String newPassword = view.getNewPassword();
try {
user.changePassword(oldPassword, newPassword);
} catch (WrongOldPasswordException e) {
view.showOldPasswordDoNotMatch();
} catch (NewPasswordTooWeakException e) {
view.showNewPasswordIsWeak();
}
}
}
If the changePassword
method returns boolean with success/fail, my presentation layer does not know the reason. So, I either use these exceptions, or return some sort of Value Object.
If not checked exceptions (something I read that it is considered "bad practice"), then what?
If I use unchecked exceptions, then the code will be the same but the controller will have to guess for the cause of the exception (Isn't this worse)?