Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify a class with lot's of copy-pasted error handling code?

In some old Java code, I found a class that contains a lot of methods that all use the same error handling code (try-catch with a lot of error handling, logging and so on). It looks like the first method was simply copied and then the code in the try block was slightly adapted. Here is what it basically looks like:

public class myClass{

    public void doSomething() {
        try {
           //do something
        } catch (Exception e) {
          //extensive error handling
        }
    }

    public void doSomethingElse() {
        try {
           //do something else
        } catch (Exception e) {
          //extensive error handling, copy-pasted from the above method
        }
    }

}

How could this be simplified? I don't want to change the interface of the class (much), I'd just like to get rid of the copy-pasted catch blocks, so that only the code from the try block stays within the original method.

I thought about using the Factory Method pattern, where one method implements the error handling and calls the original method in the try block. But then, all calls would have to go through this method.

Any ideas?

like image 893
mort Avatar asked Feb 09 '12 11:02

mort


2 Answers

Simplify it the same way you simplify all other repeated code: Put the repeated code in a method, and call the method:

public void doSomething() {
    try {
        //do something
    } catch (Exception e) {
        handleError(e);
    }
}

public void doSomethingElse() {
    try {
        //do something else
    } catch (Exception e) {
        handleError(e);
    }
}

private void handleError(Exception e) {
    //extensive error handling
}
like image 117
aioobe Avatar answered Nov 14 '22 23:11

aioobe


You could just extract the copy-pasted code in a private method taking an Exception an an argument.

like image 27
Sebastien Avatar answered Nov 14 '22 21:11

Sebastien