Wednesday, February 16, 2011

Use template for repeated try-catch

Java's try-catch blocks are particularly common when using APIs which give an important role to checked exceptions (such as SQLException in JDBC). When using such an API, many published examples simply repeat the same try-catch code structure whenever necessary. However, it is simple to eliminate such code repetition using the template method pattern. The idea is to define the structure of the try-catch block in one place, in an abstract base class (ABC). Such an ABC is then extended whenever that particular try-catch block is needed. The concrete implementation of such an ABC will often have simple, "straight line" code.
An extended example of this technique is given in the Use template for transactions topic.
See Also :
Template method
Use template for transactions

No comments:

Post a Comment

Chitika