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?
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
}
You could just extract the copy-pasted code in a private method taking an Exception
an an argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With