O'Reilly logo

Clojure Programming by Brian Carper, Christophe Grand, Chas Emerick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Aspect-Oriented Programming

Aspect-oriented programming (AOP) is a methodology that allows separation of cross-cutting concerns. In object-oriented code, a behavior or process is often repeated in multiple classes, or spread across multiple methods. AOP is a way to abstract this behavior and apply it to classes and methods without using inheritance.

A common example is metrics. It’s often desirable to produce and record timing metrics or other debugging information for running code. There is no easy way to compose this behavior into existing functionality in object-oriented codebases, so timing code ends up being added to particular methods of interest and then (hopefully!) commented out when it’s no longer being used:

public class Foo
    public void expensiveComputation () {
        long start = System.currentTimeMillis();
        try {
            // do computation
        } catch (Exception e) {
            // log error
        } finally {
            long stop = System.currentTimeMillis();
            System.out.println("Run time: " + (stop - start) + "ms");
        }
    }
}

Logging the runtime for a method requires altering the method, edits that we’d have to make repeatedly in order to instrument multiple methods. What we’d really like is a generally applicable way to “wrap” a method with some behavior. A function or method that does this is sometimes called advice.

If we have the capability to define advice separate from the methods that that advice will apply to, we gain a lot of flexibility:

  • We can selectively apply[357] the advice on a per-method basis without modifying ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required