Java Reference
In-Depth Information
theException.printStackTrace();
}
}
If we have an exception situation, the close will fail to be executed. If we're
forced to process closes in every exception condition, we have a Split Cleaner
pattern, with the same potential for failure.
7.3.2
Solution: Pair connection with cleanup, in finally
This antipattern again calls for refactoring. To solve the problem, we perform
three discrete steps:
Refactor the program to have a single entry point and a single exit
point, to make logical slots for cleanup code.
1
Make a finally block for the connection cleanup, in the method
where it is allocated.
2
Release the resources in the finally block.
3
For listing 7.4, the refactored solution is clear. We simply add a finally block
to main with the appropriate cleanup.
Listing 7.4
A refactored Split Cleaner, pairing the connection and close
try {
Class.forName ("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
Connection con = DriverManager.getConnection(url);
Adder adder = new Adder();
float total = adder.addCosts(con);
System.out.println("Total cost: " + total);
} catch (Exception e) {
throw new RuntimeException(e.toString());
}
finally {
try {
con.close();
} catch (Exception e) {
throw new RuntimeException(e.toString());
}
}
Of course, for this program, the repair is a bit like simply repainting a Gremlin
after a head-on collision with a semi. For our BBS example, we've broken our
Search WWH ::




Custom Search