Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection or Aspect Oriented Programming to be used?

Tags:

java

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?

  1. Should i use reflection?
  2. I have heard about Aspect Oriented Programming...can AOP be used here?
  3. Should i go with the plain old switch case statements and a method to decide which method to call based on operation?
like image 207
orak Avatar asked Feb 04 '26 22:02

orak


1 Answers

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();
    }
like image 192
JB Nizet Avatar answered Feb 06 '26 12:02

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!