I have a DAO class with many methods that have a lot of repeated code along the lines of: -
public void method1(...) {
Connection conn = null;
try {
This is similiar to Vladimirs solution without anonymous classes with possibility to return value from such methods.
interface DaoOperation {
void execute() throws SQLException;
}
class Operation1 implements DaoOperation {
public void execute() {
// former method1
}
}
// in case you'd ever like to return value
interface TypedDaoOperation {
T execute() throws SQLException;
}
class Operation2 implements TypedDaoOperation {
public String execute() {
return "something";
}
}
class DaoOperationExecutor {
public void execute(DaoOperation o) {
try {
o.execute();
} catch (SQLException e) {
// handle it as you want
}
}
public T execute(TypedDaoOperation o) {
try {
return o.execute();
} catch (SQLException e) {
// handle it as you want
}
}
}