Please take a look at the following DbUtil
class example. Here are three its methods
public static void closeResults(ResultSet rs) {
if (rs != null) {
try {
if (!rs.isClosed()){
rs.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public static void closeStatement(Statement stmt) {
if(stmt != null) {
try {
if (!stmt.isClosed()) {
stmt.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public static void closeConnection(Connection conn) {
if(conn != null) {
try {
if(!conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
As you can see all 3 methods have identical logic, and I would like to make this code DRY. A new common method can be written like this
public static void closeStatement(AutoCloseable ob) {
if(ob != null) {
try {
ob.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
AutoCloseable
interface doesn't contain isClosed
method. But it is still a good practice (or even must do) to perform that check before trying to close a resource. Am I right? Can the code be simplified somehow and still perform isClosed
check?
NOTE. This is just an example of the problem. I know that AutoCloseable
interface is designed for try-with-resources technic and thus the code can be rewritten with that style and DbUtil
won't be required anymore. But I would like to clarify for myself is it even possible to do something in a similar case. For example, I would think about creating some interface, say, MyAutoCloseable
, extending AutoCloseable
one and having isClosed
method, but sure that won't work, because it wouldn't be possible to cast ResultSet
or Statement
to MyAutoCloseable
.