in our system we have an abstract class, let's call it BasicAction, which contains several abstract methods. Most important of them is called execute. It handles the requests from the JSP pages. The main handler works like this:
// Sample 1:
String actionName;// The name of action to use
Map<String, BasicAction> mapping;//The mapping of names and actual handlers
BasicAction action = mapping.get(actionName);
try {
action.execute(request);//Handle the http request from the JSP page
} catch (Exception ex) {
// Handle here any exceptions
}
Now, everything looks fine, but basically all the derived handlers implement the same code:
// Sample 1:
public class ConcreteAction extends BasicAction {
@Override
public void execute(HttpServletRequest request) {
// The managers provide the middle layer between
// web presentation and database
TrafficManager trafficManager = null;
CargoManager cargoManager = null;
try {
trafficManager = new TrafficManager();
cargoManager = new CargoManager();
// Perform here all the logic required using managers
} catch (Exception ex) {
// handle the exception or rethrow it
} finally {
// Should remove all managers clearly and release the connection
removeManager(trafficManager);
removeManager(cargoManager);
}
}
}
It seems a little bit annoying to write such blocks in every handler that I have. It seems like here we imitate the enter/exit points for each handler not as supposed to. I think what we need here is to define in the BasicAction two more abstract methods called createManagers and disposeManagers. Then the main handler would look like this:
// Sample 2:
String actionName;// The name of action to use
Map<String, BasicAction> mapping;//The mapping of names and actual handlers
BasicAction action = mapping.get(actionName);
try {
action.createManagers(); // The enter point
action.execute(request);//Handle the http request from the JSP page
} catch (Exception ex) {
// Handle here any exceptions
} finally {
action.disposeManagers(); // The exit point
}
After that, each deriving action handler can be defined like this:
// Sample 2:
public class ConcreteAction extends BasicAction {
private TrafficManager trafficManager = null;
private CargoManager cargoManager = null;
@Override
public void createManagers() {
trafficManager = new TrafficManager();
cargoManager = new CargoManager();
}
@Override
public void disposeManagers() {
removeManager(trafficManager);
removeManager(cargoManager);
}
@Override
public void execute(HttpServletRequest request) {
// Perform here all the logic required using managers
}
}
Which approach is better to use - with try-catch-finally in each handler or with standard enter/exit points.
Personally, I would go for the abstract class approach, as it sounds like the Strategy pattern. Moreover, the code is cleaner and easier to follow; plus - you are not repeating the structure over and over. But that is only my opinion, someone might suggest the other way.