Java – How to remove duplicate exception block code

exceptionsjavajava-eerefactoring

I have good number of Service and DAO classes which has the same set of 30 line exception code block which gets repeated and it shows up in Code Duplication report.

The approach which I can think of is to

  • Extract the common exception code blocks to a common method and call
    the method in one shot

    Re-organize the methods to ensure there is always one entry and exit
    point to Services or DAOs which will have just one set of exception
    code.

Are there any better ways to approach this scenario?

Best Answer

Extract the exception handling into a method:

public interface Action {
    public void execute() throws ...;
}

public static void handleErrors(Action action) throws ... {
   try {
      // setup .....
      action.execute();
   } catch (...) {
      // ...
   } finally {
      // cleanup ...
   }
}

Then call it like this:

handleErrors(new Action(){ public void execute() throws ... {
    // ...
}});

The syntax is ugly, but it's still much better than duplicating the error handling dozens of times. Anytime you are duplicating more than a couple of lines, you should stop and figure out how to avoid that duplication. In Java, this often means using interfaces and anonymous classes to pass one block of code to run inside some common control logic. The same technique can be reused to eliminate duplicated looping code.