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?
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.
public abstract class Operation {
public final Response answer(String arg1, String arg2) {
authorizeSession();
Response res;
if (authorized) {
try {
Object result = executeSpecificPart(arg1, arg2);
res = Response.ok(result).build();
}
catch (MultipleExceptions ex) {
res = handleExceptions();
}
finally {
logInDatabase();
}
}
return res;
}
protected abstract Object executeSpecificPart(String arg1, String arg2);
}
...
public Response operation1(final String arg1, final String arg2) {
initialize();
Operation op1 = new Operation() {
protected Object executeSpecificPart(String arg1, String arg2) {
...
}
};
return op1.answer();
}
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