Aspect Oriented Programming

Quick description

Advanced preprocessing, where you can say things like: "Take every method that starts with the word 'test', and add it to a list of methods to be run when testing." Allows one to centralize Cross Cutting Concerns that would otherwise appear in many different classes.

Would I be right in thinking that this could be done with Monads (On Monads)?

Yes, monads seem to be a form of Aspect Oriented Programming, since they serve to isolate a generalized computational strategy from the specifics of an algorithm. For example, in Haskell Language you can write a graph-searching procedure that can either do a depth-first search and return the first result, or do a breadth-first search and return a list of results, merely by running it in a different monad.

Longer description

AOP is motivated by "Separation Of Concerns". It enables abstraction and modularization of a different kind than OOP provides.

If we look back, using POP (Procedure-Oriented Programming), we must deal with all the concerns in a line. Though we can outsource the code into different functions, the main stream still controls all the process. This is the linear model. When OOP is introduced, we can present the world in a more natural way by describing different objects and their functions. Connections between different objects form a network, a matrix of type vs. behavior. This can be called the two-dimensional model.

How is "natural" being measured here? I am bothered by that claim.

Reply in Benefits Of Oo.

Then AOP comes along and tells us that the change from POP to OOP is not complete and the world need more dimensions. This cross-cutting, distributed code can be seen as interconnections over and beyond the two-dimensional networking that OOP produced. Rules can be well tangled with the objects they govern. If the system is small, it will not be a problem. But if the system is big enough, these crosscutting concerns can significantly bloat the objects, and AOP should be applied.

Aspect oriented programming allows one to pick out a set of "join points" within the program, and then specify code ("advice") that should run at each of these points. The set of join points is specified in the same place as the advice, keeping aspects modular. This is in contrast to multiple-inheritance object systems like CLOS or C++, where the invocation of behavior is specified by the caller, not the callee.

This allows one to achieve Once And Only Once in a new way. When a User Story is going to affect a lot of classes, describe once in an Aspect and it can affect a dozen or more different places in code. The tools distribute it to the right places. This allows one to create new views into the software system which modularize the story.

See also:

External site links:

aosd.net . Comprehensive source of conference information.

www.parc.xerox.com . Contains a few other links.

www.ccs.neu.edu . A different take.


Related work

Attribute Oriented Programming, which may accomplish most of what AOP can do with runtime generated proxies or good old code generation.

The Recursive Design concept of the Shlaer Mellor Method. They name their aspects "domains"; and the weaving process is called "translation"; but the philosophy is the same.

The Gen Voca tool.

Multi-Dimensional Separation Of Concerns: Software Engineering using Hyper Spaces by IBM. See www.research.ibm.com .

In Concept Oriented Programming, cross-cutting concerns are modularized in concepts (Concept In Cop) where concepts generalize conventional classes. Parent concepts in the hierarchy inject behaviour into their child concepts.

In a sense, Aspect Oriented Programming is the opposite of Functional Programming. The core mindset of Functional Programming is computation without relying on Side Effects; in a sense, the core mindset of aspects is adding Side Effects. Aspects are like the Decorator Pattern applied to functions.

Contributors: multiple Anonymous Donors, Ian Rae, Channing Walton, LO


Q: I develop in Vb Classic and other related technologies of Pre Dot Net days. If I am not doing Web Services do I need to care about AOP?

A: I don't know how much of an answer this is, but I'm working with a team using Mixed Code Generation with Vb Classic and Visual Basic For Applications to (among other things) embed standard error handling code throughout a program, and allow the generated code to be regeneratet/replaced later. Later on, we'll be automatically generating the target tags for expansion. Sounds a little like AOP, eh? In this case, we're using a cross-cutting technique for error handling because the language does not provide another way to remove duplication of error handling code in procedures. -- Steve Jorgensen

Q: How does AOP interact with (regular) refactoring? Most refactorings involve moving code across method boundaries, but when aspect code is potentially triggered on any method invocation, then such refactorings are no longer behaviour-preserving. Answer Me, please. -- Anders Munch

A: ??

Q: What advantage does AOP give me over OOP? As every time I hear about crosscutting concerns, weaving etc. I keep thinking I could create a singleton agent/server class to handle that aspect of the software as long as its public interface was good enough.

A: One answer might be that AoP allows the application code to be "oblivious" to the aspects woven in, whereas what you propose suggests the need for the programmer to actively (remember to) invoke the aspect server at all the appropriate times/places from within the application code. Your mention of "its public interface" prompts recall of the "built-in" AoP provided by .NET by means of attributes/interfaces. That actually raises the distinction between "black-box" and "clear-box" AoP; equating AoP with only the former perhaps tempts one to question the added-value of AoP over OOP. The book "Aspect Oriented Software Development" by Filman/Elrad et al discusses this. In AOP, one wants a separation (localization) of concerns (away) from the application-domain "component code". Here is the essence of AOP, which differentiates it from, say pre-processor macro wizardry, and other stuff:

AOP: Make "quantifiable" statements: "In component code P, whenever condition C obtains, perform action A"... ...where P is oblivious Definitions: - Quantification: basically, instantiatable delimiting expression - Obliviousness: no need for preparation/modification of P for aspects

What differentiates "native support" for AOP in Microsoft's .NET (e.g., see <msdn.microsoft.com >), from AspectC++ and AspectJ, is that the former is "black-box" AOP, whereas the latter two are "clear-box" AOP. Black-box allows aspect quantification over the *public interface* of component code (e.g., message interception based), whereas clear-box additionally quantifies over the internal (e.g., private) parsed structure of the component code (i.e., requires a near-compiler).

Q: Would Aspect Oriented Functional Programming be a useful concept, or is that just silly? Is anyone attempting something like this? -- Steve Jorgensen

A: Check out library.readscheme.org , there is a body of work about AOP and Functional Programming.


Recently, I saw a little example of changing behavior at the meta level http://www.parc.xerox.com/spl/groups/eca/pubs/papers/Kiczales-Andreas-MOP/ www.parc.xerox.com. Until then, I'd thought that meta level work was not terribly behavioral... the stuff of database people and modeling language designers. The power of being able to say that method invocations will work differently for a class of classes, or even the way that member variables are associated with an object seems phenomenal. If this sort of behavior change at the meta level thing is all that it seems to be, it could usher in much more clarity in code. -- Michael Feathers

One (simplified but useful) way of thinking about the techniques (as opposed to the philosophical goals or motivations of) Aspect Oriented Programming is that they put the power of a good debugger into your programming language. A good debugger allows you set actions (print some variables, stop, etc.) whenever a particular variable is accessed or modified or whenever the call stack looks a particular way. Similarly, a good Aspect Oriented Programming language allows you to set up replacement and/or pre/post actions (call this logging procedure, use this cached variable, etc.) whenever a particular variable is accessed or modified or whenever the call stack matches a particular pattern (gets() just called, for example). And because it's in the programming language, these constructs (which can sometimes be too slow to use in a debugger) can be made very computationally efficient.

You need only see a couple examples to realize how powerful and useful this can be. You can then treat some of the rest of the ideas of Aspect Oriented Programming as trying to tame these powerful constructs into something that won't frequently shoot you in the foot (much like Structured Programming tamed the wild goto statement).

The "I Want My AOP" (www.javaworld.com ) articles on Java World do a great job of introducing AOP concepts. It's more complicated than can be effectively communicated here. There is a mental shift that happens in order to understand AOP - sort of like the same shift that happens when you learn OOP for the first time (after programming in a procedural way). -- Ken Liu

I don't know this stuff too well, so better explanations are invited. One thing that struck me - leading on from Active Object Model - was the range of techniques they used to implement their approach, which included things like reflection and Meta Object Protocol(s). It does seem to be about making implicit details explicit. -- Dave Harris

All of the theory is nice, but Aspect Oriented Programming doesn't quite fit my dream environment, which would allow me to filter the aspects of the program I'm working on, by using fonts, italics, colors, etc. to show visually what is which aspect of given source. I believe that AOP should be woven into the IDE of Delphi or some similar language, and things can REALLY take off. -- Mike Warot

AOP IDE support is available for a long time - for example 'www.eclipse.org '


Good books on Aspect Oriented Programming and related topics:



AOP is merely another patch to cover one of OOP's numerous shortcomings. First isolate everything into a tiny package ... oh wait! now I need to relate and share things ... I know! I'll make dynamic tags at runtime. Yet another mega-overhead reflection based substitute for table design. Why not store the object relationships and tags and aspects in a table and spare us this nonsense? Tables are dynamic, they are easily grokked, you can instantly change an entire suite of object aspects in a simple sql: (update object_aspects set logging=1 where objectId in (select objectID from object_methods where method_name='Speed'). Which is better, this or manually searching through 30 objects and setting an aspect on 15 of them?

Boom. One line of code and every aspect on a filtered set of objects is changed. What a revolution! This is not new technology, it's a hack to OOP.

I'm going to assume the above rant was by Top, who detests all things Oop... the problem is that the actual relational code must be written in a language. SQL is absolutely appalling for code reuse and collecting like-code together - which, surprise surpise, is why we need better structures for the programming languages themselves. Wouldn't SQL be nicer if you could easily add the same functionality (like an exception handler or something) to every single stored procedure within a given package, without adding the same line of code to each and every sproc?

A half of the current AspectJ language (if not more) is about static crosscutting. There is no reflection, no tags, no tables - AspectJ compiler (or weaver) generates bytecode that directly calls (auto-generated) static methods that constitute functionality of the aspects. The bytecode remains finely structured separating object code from aspects (so if you ever need to debug, you exactly know which source file/method/line a particular VM instruction comes from), but is generated in a way that does not hinder aggressive JIT inlining at all, which results in CPU code that has virtually no overhead.(That reminds me the principle the C++ was initially born upon: 'every potential feature that was requiring more than a couple of memory accesses at runtime was thrown just away', but with AspectJ it's even more efficient).

I use AspectJ for years already, and each time a non-static crosscutting was coming into my mind, there always were more elegant OO solution found eliminating the need for aspect or reducing non-static aspect to a static one (there are very nice and advanced and fun to learn non-static AOP examples all over the web - but they are not simple enough to be practical, for my taste). Although for debugging/quality assurance of pure OO code non-static aspects (that are kept outside of production tree) are often the fastest thing you can mock up and get runtime information you are looking for collected.

On the other hand, nowadays I find it cumbersome to code without static aspects; there is no need to have much of them, but rather keep them on point - one aspect per 30 classes is what I generally observe, with advices applying over 33-80% of classes depending on project.

Extended Object Tcl provides an interesting view of AOP: Mixins. Mixins allow classes to be blended together. The methods of the mixin class are mixed into the the methods of the target class. This allows methods to be added to classes independent of the normal OO class hierarchy. Thus a Bat and a Bird can both have a fly method with the same implementation without forcing all mammals to have a fly method. Mixins may also applied to specific objects as well. This results in elegant code reuse that is not elegant in OO languages. If AOP has any value, it should be a way to reduce complexity overall and reuse code. --Ben Thomasson

To me the problem with the term "Aspect Oriented Programming" is that it focusses on the intent, not the methodology. Object-oriented programming is a literal description of the mechanisms involved, as is Functional or Relational programming. To me, aspect-oriented programming is really just class-metaprogramming (or procedurally-constructed classes, or whatever you want to call it) - classes that are constructed based on the features of other classes. Inheritance and generics being the most primitive forms of class metaprogramming - templates being slightly more sophisiticated, but being limited by their inability to handle the members of it's class arguments as collections of the argument class' features. Mixins are similarly limited, being a subclass of templates. The only true "AOP-enabled" functionality in most languages, it seems, codegen-through-reflection - which is occasionally done in Python, C# and Java, however in the latter languages it is generally a challenging undertaking.

Calling it class metaprogramming implies you are using Aspect Oriented atop an Object Oriented paradigm, which isn't necessarily the case. Aspect Oriented needs Object Oriented like a fish needs a bicycle...

"Aspect Oriented Programming", further, does provide a methodology, or at least as much a one as Object Oriented (which is, admittedly, scattered across such things as closures, classes, prototypes, etc.). If you read into Aspect Oriented, you'll learn that the methodology consists of: (a) identifying from the language the places that modifications may be performed (join points) (b) a means of specifying which code to modify or where to add code (point cuts), (c) a means of specifying the modification to perform (advice or inter-type declarations depending on whether the code is 'run' or not).

Even further, suppose Aspect Oriented Programming did focus on the intent. What would be the problem with this? Its intent is quite valuable; it improves coupling with the problem being solved, improves Once And Only Once, etc.

Aspect Oriented tells me nothing about what it is... the only explanations I've found of it have involve class-metaprogramming like the logging example. Objects can be concisely explained in a procedural concept - functions are associated with the struct they apply to, and access to many of the structs features are controlled to within those functions - initialization is forced - and you can base a struct upon another type of struct and thus it becomes substitutable, using it's own functions in the place of the first one. Generic, likewise, can be explained in terms of OOP - designing functionality based on the abilities of a type rather than specifically what type or interface it is, yet maintaining knowledge of what type it is to ensure type-safety. Aspect? Vague notions of "separations of concerns" and trivial examples involving class metaprogramming.

There isn't sufficient agreement upon even exactly what Objects are, and your procedural conception of them is neither precise nor concise. What constitutes 'Aspect', where and how aspects is useful, and why the regular use of aspects constitute a paradigm (thus the 'oriented' word) are not things that are intuitive; they require some study. While the nature of Aspects is as ill-defined as the nature of Objects, the nature of Aspects is also as well-defined as the nature of objects. The two concepts have equal power and are of an orthogonal and somewhat dualistic nature. Object-oriented code describes behavior and structure within objects, plus the signals between them. Aspect-oriented programming takes the opposite approach and operates directly upon the medium carrying the objects and propogating the signals between them. The logging example is simply a traditional example of its use. Aspect-Oriented does not involve class metaprogramming by necessity; it could work equally well in a language without classes. In any case, your dismissal of the provided examples as 'trivial' requires greater justification than you are providing, and your dismissal of Aspect Oriented as 'vague' is similarly prejudiced.

I was explaining OOP in the context of C vs the C-OOP descendants, and generics in the context of the generic add-ons to those same languages. Obviously, OOP works differently in other languages. I suppose my problem is that most of the descriptions here are a few levels too far away from the actual processes involved. "Seperation Of Concerns" is the higher goal, but in practice the main purpose is to keep related code together and maintain Once And Only Once - your logging is all in one place, and all you have to do is mark logged classes as such. Likewise, the discussion of "Aspects" themselves is more a discussion of a higher goal, whereas the actual process involved is adding functionality to programming devices (sprocs, objects, functions, whatever) wholly externally to their declaration, generally through preprocessing or other forms of metaprogramming. To be clear: I love Aspect Oriented Programming, and the devices involved... I just think that many of the labels associated with it are too high-level to allow the neophyte to understand what's going on. I suppose I'm just arguing over terminology... which is rather pointless in retrospect.

Separation Of Concerns is also a goal in Object Oriented, as are keeping related code together and maintaining Once And Only Once. You are correct in asserting that "Separation Of Concerns" is too high a level goal to define Aspects. The notion of Aspects were created to address, in particular, those Cross Cutting Concerns that (quite literally) cannot be defined in one location using object oriented, functional, procedural, or various other paradigms. Aspects are vaguely defined as instantiations of whatever mechanism is available to address these cross-cutting concerns.

Since logging isn't a sufficient example to your tastes, consider that aspect oriented programming (in its maturity) would easily support some of the following: transparent network security, transactions, persistence; installing checks for limited resources (running out of memory, energy, etc.), locating valid yield points in cooperative multi-threading, etc. - anything that requires code analysis and widespread alterations. It can impose policies without breaching the problem domain for which the original code is written. A convenient object oriented language can anticipate and aid in providing some of these needs, but is unable to anticipate all that might be desired... and still unable to fully separate concerns (since you'd now need to go mark "logging" on every class you want it on, and cannot define such things as wanting only logging on, say, those method calls to class y that are called from within class z).


I believe that a great number of very interesting things will come out of studying type-systems that will be very relevant to Aspect Oriented Programming. Specification of join points, cut points, advice, etc. can be arbitrarily more sophisticated than they are today. In using advanced types, we'll provide better means of identifying and specifying useful transforms, and grow ever closer to modifying whole processes and systems of processes as true, First Class objects. (Among other things, it might be possible to write an Aspect Oriented Operating System.) Studies into Sub Structural Types (that delimit the use of values across space and time) and behavioral types (protocols, emergent behaviors, etc.) and Policy/Purpose types (that abstract the 'why' to a particular operation, define 'value' for computations, etc.) and more are essential to bringing this to full power.


Java Language could have been the ideal language for this - Java 1.1 implemented the minimal subset of features required for implementing an OOP concept, but with nearly no features added to ease code-reuse. Said code-reuse could have been the domain of external tools. That could have let it be the ideal target for class-metaprogramming... unfortunately, Sun never officially included such metaprogramming tools, leaving it up to a mishmash of 3rd parties, and so people ended up in the horrific ghetto of verbose hand-written Java Language.


AOP is just what Python calls "decorators", along with some extra magic to specify where to apply a decorator.


After reading the full page, I must admit I still see Aspect Oriented Programming as a hack to OOP. Certainly, hacks can be of value to manipulate the code after it is compiled (for instance to plug security separately from the source coding when it is done ) or to work at the meta level (i.e. the definition of classes), but well, it is strange so few of us need this kind of programming. If OOP was a success, AOP let a lot of people a bit puzzled. It is as if a lot of us were feeling something was going on there, something intellectually interesting but something that is still not worth using :-) Indeed, I never needed AOP to solve a problem that could not be solved by standard design patterns. I imagine I don't write the adequate kind of code to understand the full interest of it. But I come back to it from time to time since I saw the first demo in INRIA back in 2000 or so. --Olivier Rey


See original on c2.com