AspectJ: Testing that Classes Implement All Required Interfaces

Posted by Dean Wampler Sun, 25 Feb 2007 15:31:00 GMT

There was a recent post to the aspectj-users group from “Frustrated Newbie” who was trying to write a declare error that would enforce the requirement that all classes implementing one interface, let’s call it Foo, also implement a second interface Bar. He tried something like the following:
declare error: within(*..Foo+) && !within(*..*Bar+):
This doesn’t work, mostly because interfaces don’t have much real code associated with them, so there aren’t enough join points to match.

As an experiment (which he tried…), if you drop the second expression, leaving just within(*..Foo+) you get an error just on the Foo interface, not on any implementing classes or extending interfaces.

Through trial and error, I figured out that if you put these interfaces in dedicated packages, say ..foo and ..bar, respectively, the following does work:
declare error: within(*..foo.*+) && !within(*..foo.*) && !within(*..bar.*+):
The second expression !within(*..foo.*) prevents errors on the interfaces in package foo itself.

This isn’t especially obvious and you may find it inconvenient to package your interfaces like this, but it does work. Actually, there’s a good case to be made for putting interfaces in separate packages like this, based on the Stable Abstractions Principle (PDF, see also here).

Posted in ,  | 3 comments