INightmare's Blog

Ninja Aspects

Aspect oriented programming is by no doubt a powerful tool when used correctly. However, it can lead to problems when using, what I call - ninja aspects.

Ninja aspects are aspects, that are there in the code base waiting to strike without a programmer even knowing it.

A popular way to use transactions with Spring is by using its @Transactional annotation. Annotation tells a programmer, that annotated method (or all class methods if annotation is at a class level) should be decorated with transaction handling code. Annotation is a very visible way of saying “an advice is applied here”.

class Test {
    public void transactionalMethod() {
        // ...

Lets take the same example and apply a ninja aspect.

<bean id="test" class="Test"/>

<tx:advice id="txAdvice" transaction-manager="txManager">
  <tx:method name="transactionalMethod"/>

 <aop:pointcut id="testPointcut" expression="execution(* Test.*(..))"/>
 <aop:advisor advice-ref="txAdvice" pointcut-ref="testPointcut"/>

Now, we don’t need the annotation and transaction handling advice is still applied. This makes the programmer looking to the class Test unaware of such behavior. It is possible that the mentioned programmer changes the body of the method in the way, that it does not require transactions (for example, instead of taking information from the database it now uses a web service), but he is not aware, so transaction handling stays. If the aspect is transactions, we just loose some performance (potentially even call the database to commit the empty transaction), but aspects might be more serious than that. They can lead to unexpected (from the unsuspecting programmers point of view) behavior and make the code harder to understand. Of course, we will deduct from the stack trace, that the class is decorated with an AOP proxy, however that leaves us with the challenge to actually locating the advice.

It is very important to make all aspects visible, otherwise they can strike from the shadows and leave an unsuspecting programmer wondering, what the hell happened…