I am working on a java web application and I have a few questions regarding design.
Basically in its current version, it relies heavily on catching exceptions to determine the flow of control.
For instance in one of my spring service classes, I have the following method that checks whether an email given as a parameter exists in the database.
@Override
public boolean validateEmailAddressDoesNotExist(String accountEmailAddress) {
try {
return !dao.checkIfEmailAddressAlreadyExists(accountEmailAddress);
} catch (NoResultException re) {
log.error("NoResultException", re);
} catch (RuntimeException re) {
log.error("RuntimeException", re);
}
return true;
}
//from "dao" class
public boolean checkIfEmailAddressAlreadyExists(String accountEmailAddress) {
return (loadAccountFromAccountEmailAddress(accountEmailAddress) == null ? false : true);
}
//also from "dao" class
public Account loadAccountFromAccountEmailAddress(String accountEmailAddress) {
return entityManager.createNamedQuery("Account.findByEmailAddress", Account.class).setParameter("accountEmailAddress", accountEmailAddress).getSingleResult();
}
I suspect that my current design is probably wrong but I would be grateful to read your comments and opinion about it and to what extent you believe it is flawed.
Validation methods in your service model should not be catching exceptions. That’s bad for a few reasons:
It’s not an exceptional condition. “No results” is a common situation.
It indirectly couples your validation to the implementation of the framework’s data-retrieval methods. To see why that’s not good, imagine if your framework changes such that it now raises a
EmptyResultSetException. You’d have to update all your validation methods. Yikes!You can’t necessarily help it if your underlying framework raises exceptions to indicate “no results”, but you can certainly control what
checkIfEmailAddressAlreadyExistsdoes.Change this method so that it returns
trueif the address exists, andfalseif it doesn’t or if no results were found.