Aspect-oriented programming
Technique · Chapter 9
Aspect-oriented programming (AOP)
Section titled “Aspect-oriented programming (AOP)”AOP is a paradigm created to handle the scattering and tangling of boilerplate code (such as cross-cutting concerns) in object-oriented programming. It originated in research led by Gregor Kiczales and colleagues at Xerox PARC.
Core concepts
Section titled “Core concepts”| Concept | Meaning |
|---|---|
| Aspect | The modularized cross-cutting concern itself (e.g. logging, caching) |
| Join point | A point between logical steps of the program — e.g. after startup, before/after object creation, before/after a method call, before program end |
| Pointcut | A set of join points; can be simple (before/after any method in a class) or complex (after any public method except add/update/delete) |
| Advice | The code that actually performs the cross-cutting concern (e.g. the statements that write to the log) |
Types of advice
Section titled “Types of advice”- Before advice (on start) — runs before a join point; cannot stop flow reaching the join point.
- After returning (on success) — runs after a join point completes with no exception.
- After throwing (on error) — runs if an exception occurred.
- After advice (finally) — runs after the join point exits, success or exception.
- Around advice — surrounds the join point; can run logic before and after, and can prevent execution by returning its own value or throwing.
Weaving
Section titled “Weaving”Weaving applies the advice to the core concern’s logic. Each concern’s code lives in a single place, so a change (e.g. to logging) is made once rather than in every core concern that uses it. Weaving happens at compile-time or at runtime.
Compile-time weaving
Section titled “Compile-time weaving”- After normal compilation (DLL/EXE), an AOP-tool post-processor adds the aspects, guided by configuration (where to apply advice).
- Result contains core logic + all advice.
- Pro: no runtime weaving overhead. Con: aspects can’t be changed at runtime via configuration.
Runtime weaving
Section titled “Runtime weaving”- Weaving happens after the app starts; no post-compilation changes to binaries.
- Works like the decorator pattern, but the AOP tool generates a dynamic proxy implementing the target’s interface and delegates to it while weaving in advice — developers don’t hand-write decorators.
- Pro: no post-compilation process; aspects reconfigurable at runtime. Con: some runtime weaving overhead.
Related
Section titled “Related”- One of the three approaches in Implementing cross-cutting concerns.
Citations
Section titled “Citations”- Software Architect’s Handbook (Packt, 2018), Ch.9 “Aspect-oriented programming”, pp. 706-711.