Java Remove repeated try, catch, finally boilerplate from DAO

前端 未结 4 1003
心在旅途
心在旅途 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:30

    Create an interface for ex. Executable:

     public interface Executable() {
    
       void exec() throws SqlException();
    
     }
    

    Refactor each of your dao method to :

    public void method1() {
       execute(new Executable() {
    
         @Override
         public void exec() throws SqlException() {
              // your code here
         }
      });
      } 
    

    Create the following method execute in your DAO:

    private void execute(Executor ex) {
        try {
          ex.exec();
        } catch(...) {
          ...
        } finally {
           ...
        }
    }
    

提交回复
热议问题