I am using Aspectj for project-wide policy enforcement.
One thing I am trying to implement now is that there should be no logic in any setter methods except simple validation with Guava's Preconditions.check*
methods.
public pointcut withinSetter() :
withincode(public void set*(*));
public pointcut inputValidation() :
call(public void Preconditions.check*(*));
public pointcut setFieldValue() : set(* *);
public pointcut entity() : within(com.mycompany.BaseEntity+);
declare warning :
entity() && withinSetter() && !setFieldValue() && !inputValidation():
"Please don't use Logic in Setters";
This works as expected, generating warnings for any non-setter code. However, it fails for constructs like this:
public void setFoo(final String newFoo) {
Preconditions.checkNotNull(newFoo); // this is OK
Preconditions.checkArgument(
newFoo.matches("\\p{Alpha}{3}"), // this generates a warning
// because String.matches()
// is called
"Foo must have exactly 3 characters!");
this.foo = newFoo;
}
So what I am looking for is a construct that would allow any code, as long as it happens inside the parameters to a Preconditions.check*
call. Is there such a pointcut?
I know it is an old question, but I just stumbled across it while searching for something else.
The answer is no, because in JVM bytecode there is no such thing as "logic inside a
check*
call". For example,newFoo.matches(..)
is evaluated before the result is passed toPreconditions.checkArgument(..)
, very much like this:If the code was written like this, you would issue a warning anway, so why not if the same Java code, possibly resulting in similar or identical byte code, is written as a nested call?
;-)
Update: I have created a little example:
If you dump the byte code using
javap -c Application
you see this:As you can see, the byte code of lines 3-13 versus 16-24 in the dump is identical except for the storing and re-loading of the boolean value. Maybe this illustrates what I have said before.