Java Remove repeated try, catch, finally boilerplate from DAO

前端 未结 4 1023
心在旅途
心在旅途 2021-01-06 08:06

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 {
             


        
4条回答
  •  春和景丽
    2021-01-06 08:22

    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
            }
        }
    }
    

提交回复
热议问题