Template Method Extraction¶
Template Method Extraction is a refactoring technique that utilizes functional programming concepts to isolate and reuse common workflow logic, such as transaction management and resource handling. By encapsulating these workflows, developers can pass specific business logic as parameters, typically using method references^[600-developer-java-java8-java8-lambda01.md].
This approach effectively separates the "template" or "skeleton" of an operation (e.g., obtaining a database connection, handling commits/rollbacks, and closing resources) from the variable parts of the logic (e.g., the specific SQL execution or DAO call)^[600-developer-java-java8-java8-lambda01.md].
Implementation¶
The implementation typically involves defining a Functional Interface and a generic execution class (the Template Method).
- Functional Interface: A custom interface (e.g.,
BiFunctionUnchecked) is defined to accept the necessary context (like a databaseConnectionand parameters) and return a result, while allowing checked exceptions (likeSQLException)^[600-developer-java-java8-java8-lambda01.md]. - The Template Class: A generic class (e.g.,
DefaultBO) contains static methods that manage the lifecycle of the operation^[600-developer-java-java8-java8-lambda01.md]. - Method References: The specific business logic is passed using the "Class Name - Static Method Name" syntax^[600-developer-java-java8-java8-lambda01.md].
Example¶
In the provided example, DefaultBO acts as the template, managing connections and transactions. The specific data access logic is abstracted into the DAO layer and passed into the template^[600-developer-java-java8-java8-lambda01.md].
Workflow Modes¶
The template class usually provides different modes to handle various data access scenarios^[600-developer-java-java8-java8-lambda01.md]:
- Read Operations: A method that retrieves a read connection, executes the provided function, and ensures the connection is closed in a
finallyblock^[600-developer-java-java8-java8-lambda01.md]. - Write Operations: A method that retrieves a write connection, disables auto-commit, executes the function, explicitly commits the transaction, and includes error handling for rollback^[600-developer-java-java8-java8-lambda01.md].
Code Usage¶
Instead of writing repetitive try-catch-finally blocks in every service method, the client code calls the generic template with the specific DAO method^[600-developer-java-java8-java8-lambda01.md]:
// Client Code
private static List<OhSystemConfig> simpleBoMethod(Map<String, Object> map) throws Exception {
return DefaultBO.read(map, BeanDao::currentSql);
}
Sources¶
600-developer-java-java8-java8-lambda01.md
Related Concepts¶
- [[Functional Programming]]
- Design Patterns
- [[Lambda Expressions]]