Java Reference
In-Depth Information
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.
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.
Make a finally block for the connection cleanup, in the method
where it is allocated.
Release the resources in the finally block.
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 ("").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 {
} 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