Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design - Check a condition before executing every method

I have a POJO named Document.java with 100+ member variables. There is a transformation layer, where I get the required data, transform it and store it in the Document class.

In the tranformation layer, I would like to set a member variable only if satisfies a certain criteria (based on available context).

So it would look something like this:

if(shouldGetExecuted1(context.getXXX())){
  document.setField1(tranformDataForField1(availableData1));
}

if(shouldGetExecuted2(context.getXXX())){
  document.setField2(tranformDataForField2(availableData2));
}

I want to do this for all the 100+ fields. Is there a clean way to do this?

Additional information

I don't want to use Strategy here as it would create too many classes as the no of strategies grow.

like image 878
user2989124 Avatar asked Aug 10 '15 22:08

user2989124


1 Answers

Try to use AOP. AspectJ allows you to define pointcuts (for example, some filtered set of methods) and control their execution via advices (before method call, after, around):

@Aspect
class ClassName {
...

@PointCut("call(public void ClassName.*(..))") //includes all void methods of ClassName object 
public void myPointCut(){}

@Around("myPointCut()")
public void myLogicMethod(ProceedingJoinPoint thisJoinPoint) {

    if(shouldGetExecuted1(context.getXXX())){
        thisJoinPoint.proceed()
    }
}
}

Here thisJoinPoint.proceed() will execute the body of the intercepted method.

Read docs about how to define pointcuts. In this example the same logic will be applied to all void methods of this class. You can define more accurate pointcuts via special expressions to provide different logic for each.

like image 68
ka4eli Avatar answered Oct 28 '22 20:10

ka4eli