Objective: ensure all code paths either throw or return a valid connection; I am trying to explicitly avoid at all costs the connection object to ever return as “null”.
This is the best I could come up with:
public class JdbcConnectionManager {
public static class JdbcConnectionFailureException extends Exception {
private static final String JDBC_CONNECTION_INVALID_MESSAGE =
"JDBC connection invalid, checked with timeout value of: "
+ JdbcConnectionManager.JDBC_CONNECTION_VALIDATION_TIMEOUT_IN_SECONDS;
private static final long serialVersionUID = 1L;
public JdbcConnectionFailureException(String message) {
super(message);
}
public JdbcConnectionFailureException(Throwable throwable) {
super(throwable);
}
}
private static int JDBC_CONNECTION_VALIDATION_TIMEOUT_IN_SECONDS = 3;
public static Connection getJdbcConnection(
JdbcConnectionParameters jdbcConnectionParameters)
throws JdbcConnectionFailureException {
try {
if (jdbcConnectionParameters
.driverNeedsHelpRegisteringUsingClassForName()) {
Class.forName(jdbcConnectionParameters
.getClassForNameDriverRegistrationString());
}
Connection jdbcConnection =
DriverManager.getConnection(jdbcConnectionParameters
.getJbdcConnectionUrl());
if (!jdbcConnection
.isValid(JdbcConnectionManager.JDBC_CONNECTION_VALIDATION_TIMEOUT_IN_SECONDS)) {
throw new JdbcConnectionManager.JdbcConnectionFailureException(
JdbcConnectionManager.JdbcConnectionFailureException.JDBC_CONNECTION_INVALID_MESSAGE);
}
// TODO: perform further validation on the connection
return jdbcConnection;
} catch (ClassNotFoundException classNotFoundException) {
throw new JdbcConnectionManager.JdbcConnectionFailureException(
classNotFoundException);
} catch (SQLException sqlException) {
throw new JdbcConnectionManager.JdbcConnectionFailureException(
sqlException);
}
}
}
Am I rock-solid here? Is there a better, more concise/elegant/robust way to ensure “connection” is never “null”?
EDIT:
I added a jdbcConnection.isValid() check but I have left out input validation. I’ll do that in the actual code.
It would be much clearer to just return the connection from inside the try block:
EDIT : to answer your question about dead code:
jdbcConnection can NOT be null at this place, because if it was null, a NPE would have been thrown at the line