Skip to main content

The AOP Elevator Speech

Posted by crazybob on September 20, 2004 at 8:37 AM PDT

So what's this AOP thing I've been hearing about?

Aspect-Oriented Programming (AOP) picks up where OOP leaves off. AOP enables me to abstract boilerplate code into one place as opposed to scattering it throughout my code base. AOP lets me say, "apply some code that follows this generalized pattern to all of these places."

Say for example that I have a form class that holds data from a screen. The class has multiple setter methods for the fields and an isValid() method that returns true if the form fields are valid.

  class LoginForm {
    void setUserId(String userId) { ... }
    void setPassword(String password) { ... }
    boolean isValid() { ... }

My code calls the isValid() method multiple times, and it takes a non-trivial amount of time to execute (perhaps it validates against a remote system). It makes sense to cache the result and blow it away any time the form's state changes.

With traditional OO, code in each setter could delete the cached value, and the template design pattern could abstract the caching logic from isValid() into a method in a super class. Unfortunately, adding caching logic impacts all of my form classes. The more form classes, the more changes. I have to put code in every setter (running the risk of accidentally missing one), and now I have to modify the form classes to implement a template method instead of isValid(). Lastly, reusing code through inheritance couples validation caching with other such reusable functionalities in the parent classes preventing me from reusing them independently.

AOP enables me to leave my form classes untouched and to fully decouple reusable functionalities. My form classes shouldn't care that I'm caching the validation result. With AOP, I can implement the caching logic in one module and apply it at runtime or build time to all of my forms or to other places that follow a similar pattern. Each new form I add will enjoy caching for free. I've gone from a constant maintenance effort to zero effort thanks to AOP. Plus, I have a lot less code to unit test.

Piqued your interest? Take Dynaop for a spin.