Skip to content

Aspect-oriented programming

Technique · Chapter 9

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.

ConceptMeaning
AspectThe modularized cross-cutting concern itself (e.g. logging, caching)
Join pointA point between logical steps of the program — e.g. after startup, before/after object creation, before/after a method call, before program end
PointcutA set of join points; can be simple (before/after any method in a class) or complex (after any public method except add/update/delete)
AdviceThe code that actually performs the cross-cutting concern (e.g. the statements that write to the log)
  • 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 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.

  • 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.
  • 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.
  • Software Architect’s Handbook (Packt, 2018), Ch.9 “Aspect-oriented programming”, pp. 706-711.