I have developed a web service in java which contains about 30 operations. Each operation has the exact same code except for 2-3 lines. Following is a sketch of the code
public Response operation1(String arg1, String arg2)
{
initialze(); // this line will be different for each operation with different arguments
authorizeSession();
Response res;
if (authorized)
{
try
{
Object result = callMethod1(arg1, arg2); // This line is different for each operation
res = Response.ok(result).build();
}
catch( MultipleExceptions ex)
{
res = handleExceptions();
}
finally
{
logInDatabase();
}
}
return res;
}
What approach should i follow so that i dont have to write the same code in each operation?
- Should i use reflection?
- I have heard about Aspect Oriented Programming…can AOP be used here?
- Should i go with the plain old switch case statements and a method to decide which method to call based on operation?
This looks like a good candidate for the template method pattern. Define an abstract class containing the main method (final), which delegates the specific parts to protected abstract methods.
In each method of your web service, instantiate a subclass of this abstract class which only overrides the two specific abstract methods, and call the main method of this subclass instance.