Conceptcore
Aspect-oriented programming
Also called AOP, aspects, cross-cutting concerns, pointcuts and advice, weaving, interceptors.
Aspect-oriented programming puts a concern that cuts across many modules, such as logging or transactions, into one aspect, and a weaver applies its advice at the join points that a pointcut selects.
- Applies to
- core-languages
Idea
Aspect-oriented programming (AOP) puts a concern that cuts across many parts of a program into one module, called an aspect, and applies it to those parts by rule. Logging, security checks, transactions, caching and metrics are typical cross-cutting concerns: each must run in many methods, in many classes, and none belongs to any one of them. Gregor Kiczales and his colleagues at Xerox PARC named the problem in 1997. Some design decisions are "scattered throughout the code, resulting in 'tangled' code that is excessively difficult to develop and maintain", and the reason is "that they cross-cut the system's basic functionality."1 The example below keeps the audit concern out of the Account class, and applies it from outside to the methods that match a pattern:
import fnmatch
import functools
class Account:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
def report(self):
return f"balance {self.balance}"
# An aspect has two parts: a pointcut that selects methods, and advice that runs around them.
def weave(cls, pointcut, advice):
for name, member in list(vars(cls).items()):
if callable(member) and fnmatch.fnmatch(name, pointcut):
setattr(cls, name, advice(member))
def audit(method):
@functools.wraps(method)
def around(self, *args):
print(f"before {method.__name__}{args}")
try:
result = method(self, *args)
except Exception as e:
print(f"after {method.__name__}: failed: {e}")
raise
print(f"after {method.__name__}: balance {self.balance}")
return result
return around
weave(Account, "[dw]*", audit) # deposit and withdraw, but not report or __init__
acct = Account(100)
acct.deposit(50)
try:
acct.withdraw(500)
except ValueError:
pass
print(acct.report())
before deposit(50,)
after deposit: balance 150
before withdraw(500,)
after withdraw: failed: insufficient funds
balance 150
The class has no line about auditing, and the audit code has no line about accounts. The call to weave connects them: it states where the aspect applies (the methods whose names start with d or w) and what it does there (print before and after the call). A new method named deposit_all would get the audit with no change to the aspect.
How it works
Join points, pointcuts and advice. AOP names three parts. The Spring documentation defines them. A join point is "a point during the execution of a program, such as the execution of a method or the handling of an exception." Advice is the "action taken by an aspect at a particular join point." A pointcut is "a predicate that matches join points."2 An aspect groups pointcuts and advice for one concern. In AspectJ, a pointcut such as execution(* Account.with*(..)) selects the execution of all methods of Account whose names start with with, and advice marked before, after or around runs at those points.
Kinds of advice. Before advice runs before the join point. After advice runs after it, and AspectJ splits it into after a normal return, after an exception, and after either one. Around advice runs instead of the join point and decides whether, when and how many times to proceed to it. Around advice can change the arguments and the result, and it can catch exceptions, so it can do all that the other kinds do. The function around in the example is around advice.
Weaving. A weaver joins the aspects with the base code. AspectJ weaves at compile time, by changing the bytecode of the classes it compiles, or at load time, by changing classes as the JVM loads them. Spring AOP and the proxy libraries of .NET weave at run time: they put a proxy object in front of the real object, and the proxy runs the advice before it passes each call on. Python decorators and JavaScript proxies are run-time weaving by hand. Kiczales's paper describes the weaver as the part that "handles these details, instead of the programmer having to do the tangling manually."1
Inter-type declarations. AspectJ also lets an aspect add fields and methods to other classes, or declare that a class implements an interface. The AspectJ guide says that "pointcuts and advice dynamically affect program flow, inter-type declarations statically affects a program's class hierarchy".3 This makes it possible to put all the code of one concern, data as well as behavior, in one file.
Obliviousness. In full AOP, the base code does not know that aspects apply to it. This is the source of both the power and the main criticism of AOP: a reader of a method cannot see from its text what runs when it is called. Many later systems give up some of this power for clarity. They require a visible marker at each join point, such as an annotation or a decorator, so the reader sees that something more happens.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Library | |
| C | Absent | |
| C# | Standard library | |
| JavaScript | Standard library | |
| TypeScript | Native | Decorators on classes, methods and fields wrap or replace them; Proxy as in JavaScript. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Library | AspectJ and Spring AOP work on Kotlin classes on the JVM; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Idiom | BEFORE and AFTER triggers add behavior to every change of a table, such as audit rows, without a change to the statements that make the changes. |
| Bash | Idiom | Trap with DEBUG runs a command before each simple command, and trap with RETURN runs one when a function returns. |
| PowerShell | Idiom | A proxy function with the same name as a cmdlet wraps it with extra steps; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | HTML has no functions to advise. |
| CSS | Does not apply | CSS has no functions to advise; a rule that applies to many selectors is a form of cross-cutting style, not of advice. |
| Regular expressions | Does not apply | Regular expressions have no functions to advise. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | idiom | decorators, setattr on classes |
| JavaScript | stdlib | Proxy and Reflect |
| TypeScript | native | decorators; Proxy |
| Java | library | AspectJ, Spring AOP; java.lang.reflect.Proxy in the JDK |
| Kotlin | library | as Java |
| C# | stdlib | DispatchProxy; weavers in libraries |
| Go | idiom | middleware that wraps a handler |
| Rust | idiom | wrapper functions; attribute macros in crates |
| C | absent | wrapper functions; instrumentation hooks of the compiler and the linker |
| C++ | idiom | generic wrappers; AspectC++ |
| Bash | idiom | trap with DEBUG and RETURN |
| PowerShell | idiom | proxy functions |
| SQL | idiom | BEFORE and AFTER triggers |
| Regex | n/a | no functions |
| HTML | n/a | no functions |
| CSS | n/a | no functions |
Java is the home of AOP. AspectJ came from the group at Xerox PARC that named the idea, and the AspectJ guide states its aim: "Aspect-oriented programming is a way of modularizing crosscutting concerns much like object-oriented programming is a way of modularizing common concerns."3 Most Java programmers meet AOP through Spring, where annotations such as @Transactional and @Cacheable mark methods, and proxies apply the advice. The Java file of this page shows the main limit of proxies: a call from inside the object to another of its methods does not pass through the proxy, so it gets no advice.
The other core languages have no weaver, and they use the parts of AOP that their features allow. Python decorators, TypeScript decorators and C# attributes put a visible marker on each join point, and a function or a framework adds the behavior. JavaScript Proxy and C# DispatchProxy intercept calls at run time. Go middleware, and wrapper functions in Rust, C and C++, are around advice that the programmer applies by hand. These forms keep the concern in one place, which is the main benefit of AOP, but they give up pointcuts that select join points by pattern across the whole program.
import functools
def tag(label):
def aspect(fn):
@functools.wraps(fn)
def around(*args):
print(f"enter {label}")
result = fn(*args)
print(f"leave {label}")
return result
return around
return aspect
@tag("outer")
@tag("inner")
def work(x):
print("work", x)
return x * 2
print(work(21), work.__name__)
enter outer
enter inner
work 21
leave inner
leave outer
42 work
This code runs but gives a wrong answer on purpose.
def log(fn):
def around(*args):
print("calling", fn.__name__)
fn(*args)
return around
@log
def total(xs):
return sum(xs)
print(total([1, 2, 3]), total.__name__)
calling total
None around
- Verdict: idiom. Python has no pointcuts or weaver in the language, but decorators and
setattron classes give before, after and around advice. The functionweavein the first block of this page picks methods by a name pattern, as a pointcut does. - Stacked decorators apply from the bottom up, so the top one runs first and finishes last. The order of aspects is the order of the decorators.
- In the wrong block, the advice calls the function but does not return its result, so every call returns
None. It also does not usefunctools.wraps, so the function loses its name. An around advice must return what the advised function returns.
#include <iostream>
#include <string>
#include <utility>
template <typename F>
auto around(std::string name, F f) {
return [name = std::move(name), f = std::move(f)](auto&&... args) {
std::cout << "before " << name << "\n";
auto result = f(std::forward<decltype(args)>(args)...);
std::cout << "after " << name << " -> " << result << "\n";
return result;
};
}
int main() {
auto area = around("area", [](double w, double h) { return w * h; });
auto checked = around("checked", [&](double w, double h) {
if (w < 0 || h < 0) return -1.0;
return area(w, h);
});
std::cout << checked(3, 4) << "\n";
}
before checked
before area
after area -> 12
after checked -> 12
12
- Verdict: idiom. C++ has no aspects. A generic lambda that wraps another callable gives around advice, and templates let the compiler inline it. AspectC++ is a research weaver that adds AspectJ-style aspects to C++.
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Main {
interface Account {
void deposit(int amount);
void depositTwice(int amount);
int balance();
}
static class SimpleAccount implements Account {
private int balance;
public void deposit(int amount) { balance += amount; }
public void depositTwice(int amount) { deposit(amount); deposit(amount); }
public int balance() { return balance; }
}
public static void main(String[] args) {
Account target = new SimpleAccount();
InvocationHandler audit = (proxy, method, params) -> {
if (method.getName().startsWith("deposit")) {
System.out.println("before " + method.getName() + " " + params[0]);
}
return method.invoke(target, params);
};
Account account = (Account) Proxy.newProxyInstance(
Account.class.getClassLoader(), new Class<?>[] {Account.class}, audit);
account.deposit(10);
account.depositTwice(5);
System.out.println("balance " + account.balance());
}
}
before deposit 10
before depositTwice 5
balance 20
- Verdict: library. AspectJ adds aspects, pointcuts and advice to Java and weaves them into the bytecode at compile time or at class load time. Spring AOP gives a subset with proxies. The JDK gives the base of the proxy approach:
java.lang.reflect.Proxymakes an object that sends each call on an interface to anInvocationHandler. - The output shows a pitfall of all proxy-based AOP.
depositTwicecallsdeposittwice, but these calls go tothis, the real object, and not through the proxy. Only the outer call is advised. AspectJ's weaving changes the bytecode of the class, so it advises internal calls too.
#include <stdio.h>
typedef int (*op)(int, int);
static int add(int a, int b) { return a + b; }
static int mul(int a, int b) { return a * b; }
struct advised {
const char *name;
op fn;
};
static int call(const struct advised *f, int a, int b)
{
printf("before %s(%d, %d)\n", f->name, a, b);
int r = f->fn(a, b);
printf("after %s -> %d\n", f->name, r);
return r;
}
int main(void)
{
const struct advised ops[] = { { "add", add }, { "mul", mul } };
int x = call(&ops[0], 2, 3);
int y = call(&ops[1], x, 4);
printf("%d\n", y);
return 0;
}
before add(2, 3)
after add -> 5
before mul(5, 4)
after mul -> 20
20
- Verdict: absent. C has no way to attach code to a function without changing its callers. A wrapper that takes a function pointer gives advice for calls that go through it. Toolchains add a few hooks outside the language: the GCC and Clang flag
-finstrument-functionscalls two hook functions at the entry and exit of every function, and the GNU linker option--wrapsends calls of a symbol to a wrapper.
using System.Reflection;
IAccount account = Audit<IAccount>.Wrap(new Account());
account.Deposit(10);
account.Withdraw(4);
Console.WriteLine($"balance {account.Balance}");
public interface IAccount
{
int Balance { get; }
void Deposit(int amount);
void Withdraw(int amount);
}
class Account : IAccount
{
public int Balance { get; private set; }
public void Deposit(int amount) => Balance += amount;
public void Withdraw(int amount) => Balance -= amount;
}
public class Audit<T> : DispatchProxy where T : class
{
T target = null!;
public static T Wrap(T target)
{
var proxy = Create<T, Audit<T>>();
((Audit<T>)(object)proxy).target = target;
return proxy;
}
protected override object? Invoke(MethodInfo? method, object?[]? args)
{
if (method!.Name is "Deposit" or "Withdraw")
Console.WriteLine($"before {method.Name}({args![0]})");
return method.Invoke(target, args);
}
}
before Deposit(10)
before Withdraw(4)
balance 6
- Verdict: stdlib.
System.Reflection.DispatchProxymakes a class at run time that implements an interface and sends each call toInvoke. The pointcut here is the test on the method name. The propertyBalanceis the methodget_Balance, so it is not advised. Libraries such as Castle DynamicProxy, and compile-time weavers such as PostSharp and Metalama, give more complete AOP.
const account = {
balance: 100,
deposit(n) { this.balance += n; },
withdraw(n) { this.balance -= n; },
report() { return `balance ${this.balance}`; },
};
const pointcut = /^(deposit|withdraw)$/;
const advised = new Proxy(account, {
get(target, name, receiver) {
const value = Reflect.get(target, name, receiver);
if (typeof value !== "function" || !pointcut.test(name)) return value;
return function (...args) {
console.log(`before ${name}(${args})`);
const result = value.apply(this, args);
console.log(`after ${name}: balance ${target.balance}`);
return result;
};
},
});
advised.deposit(50);
advised.withdraw(30);
console.log(advised.report());
before deposit(50)
after deposit: balance 150
before withdraw(30)
after withdraw: balance 120
balance 120
- Verdict: stdlib. A
Proxyintercepts every property access on an object, so thegettrap can wrap the methods that a pattern selects.Reflect.getperforms the normal access. Code that holds a reference to the original object, and not to the proxy, does not see the advice.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
type middleware func(http.Handler) http.Handler
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("log:", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
func requireKey(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Key") != "secret" {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func chain(h http.Handler, ms ...middleware) http.Handler {
for i := len(ms) - 1; i >= 0; i-- {
h = ms[i](h)
}
return h
}
func main() {
hello := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "hello")
})
app := chain(hello, logging, requireKey)
for _, key := range []string{"", "secret"} {
req := httptest.NewRequest("GET", "/hello", nil)
req.Header.Set("X-Key", key)
rec := httptest.NewRecorder()
app.ServeHTTP(rec, req)
fmt.Println(rec.Code, strings.TrimSpace(rec.Body.String()))
}
}
log: GET /hello
403 forbidden
log: GET /hello
200 hello
- Verdict: idiom. Go has no aspects, annotations or proxies. Middleware is the Go form of around advice: a function that takes a handler and returns a handler that does work before and after it, or does not call it at all. The concern lives in one place, and
chainapplies it to any handler. The selection of join points is explicit: only the handlers passed throughchainget the advice.
use std::cell::Cell;
use std::fmt::Debug;
fn logged<A: Debug, R: Debug>(name: &'static str, f: impl Fn(A) -> R) -> impl Fn(A) -> R {
move |a| {
println!("before {name}({a:?})");
let r = f(a);
println!("after {name} -> {r:?}");
r
}
}
fn counted<'a, A, R, F: Fn(A) -> R + 'a>(count: &'a Cell<u32>, f: F) -> impl Fn(A) -> R + 'a {
move |a| {
count.set(count.get() + 1);
f(a)
}
}
fn main() {
let calls = Cell::new(0);
let square = counted(&calls, logged("square", |x: i32| x * x));
square(3);
square(4);
println!("calls: {}", calls.get());
}
before square(3)
after square -> 9
before square(4)
after square -> 16
calls: 2
- Verdict: idiom. Rust has no run-time interception. Higher-order functions that wrap a closure give around advice, and the compiler inlines them, so they cost nothing at run time. Attribute macros give the closest form to AspectJ: the
#[instrument]attribute of thetracingcrate rewrites a function to add logging around its body.
Variations and related ideas
- Decorators. A function that wraps a function, or a class that wraps an object with the same interface. See the decorator pattern and higher-order functions.
- Annotations and attributes. Metadata on declarations that a framework reads to apply behavior. See annotations.
- Middleware and interceptors. Chains of handlers in web frameworks, RPC systems and message buses, each of which can act before and after the next one.
- Dependency injection containers. Containers often apply aspects when they build objects, by giving out proxies. See dependency injection.
- Metaobject protocols. Kiczales's earlier work let programs change how the language runs method calls and object creation. AOP grew out of it. See runtime reflection.
- Template method. A base class fixes the steps around a hook that subclasses fill in. It is advice by inheritance, applied to one class at a time. See the template method pattern.
- Context managers and defer.
with,using,deferandfinallyput code before and after a block at one place in the source. See defer and finally.
Pitfalls
- Invisible behavior. With pointcuts that match by pattern, a reader of a method cannot see which advice runs on it. Use tools that show the advice on each method, or require a marker such as an annotation at each join point.
- Fragile pointcuts. A pointcut that matches names by pattern breaks silently when a method is renamed, and it can start to match a new method by accident. Match on annotations or types, not on names.
- Self-invocation in proxies. A call from inside an object to its own method goes to
this, not to the proxy, so the advice does not run. The Java file shows this. Spring's@Transactionalon a method called from the same class is a well known case. - Lost results and exceptions. Around advice must return the result of the join point and must let exceptions through unless it handles them on purpose. The wrong block in the Python file returns
Nonefor every call. - Order of aspects. When two aspects apply to one join point, the order matters: a retry aspect outside a transaction aspect retries the whole transaction, but inside it retries only part of it. State the order explicitly.
- Debugging. Stack traces contain proxy and advice frames, and a debugger can step into woven code that is not in any source file.
Cost
Compile-time and load-time weaving put the advice into the bytecode, so the cost at run time is the cost of the advice itself plus a method call or two. Load-time weaving adds time at startup, because each class is changed as it loads. Proxies cost more on each call: a reflective call through Proxy or DispatchProxy boxes the arguments into an array and calls the target by reflection, which is many times slower than a direct call. Libraries that generate bytecode for proxies reduce this cost. Wrapper functions in Rust and C++ are usually inlined and cost nothing. The larger cost of AOP is in understanding: each aspect is one more thing that a reader must know about to predict what a call does.
History
AOP came from research on reflection and metaobject protocols at Xerox PARC. Gregor Kiczales, who had worked on the metaobject protocol of the Common Lisp Object System, led a group that presented "Aspect-Oriented Programming" at ECOOP in June 1997.1 The paper built several domain-specific aspect languages and a weaver for each. In one of its examples, a weaver of 1959 lines produced code with performance "comparable to a 35213 line manually tangled version".1 The group then built AspectJ, a general aspect language for Java, and released it from about 1998. AspectJ moved to the Eclipse Foundation in 2002. The Spring Framework made proxy-based AOP part of Java enterprise programming from 2004, and annotations in Java 5 gave a way to mark join points in the source. After the 2000s, interest in full AOP fell, and its ideas lived on in decorators, middleware, annotations and interceptors in many languages.
References
- Aspect-Oriented Programming, Gregor Kiczales and others, ECOOP 1997, LNCS 1241, abstract; section 5
- AOP Concepts, Spring Framework reference, AOP Concepts
- Getting Started with AspectJ, The AspectJ Programming Guide, Introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag A05RNF Edit this page History Report an error Markdown