Aspect-oriented programming explained

In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding behavior to existing code (an advice) without modifying the code, instead separately specifying which code is modified via a "pointcut" specification, such as "log all function calls when the function's name begins with 'set. This allows behaviors that are not central to the business logic (such as logging) to be added to a program without cluttering the code of core functions.

AOP includes programming methods and tools that support the modularization of concerns at the level of the source code, while aspect-oriented software development refers to a whole engineering discipline.

Aspect-oriented programming entails breaking down program logic into cohesive areas of functionality (so-called concerns). Nearly all programming paradigms support some level of grouping and encapsulation of concerns into separate, independent entities by providing abstractions (e.g., functions, procedures, modules, classes, methods) that can be used for implementing, abstracting, and composing these concerns. Some concerns "cut across" multiple abstractions in a program, and defy these forms of implementation. These concerns are called cross-cutting concerns or horizontal concerns.

Logging exemplifies a cross-cutting concern because a logging strategy must affect every logged part of the system. Logging thereby crosscuts all logged classes and methods.

All AOP implementations have some cross-cutting expressions that encapsulate each concern in one place. The difference between implementations lies in the power, safety, and usability of the constructs provided. For example, interceptors that specify the methods to express a limited form of cross-cutting, without much support for type-safety or debugging. AspectJ has a number of such expressions and encapsulates them in a special class, called an aspect. For example, an aspect can alter the behavior of the base code (the non-aspect part of a program) by applying advice (additional behavior) at various join points (points in a program) specified in a quantification or query called a pointcut (that detects whether a given join point matches). An aspect can also make binary-compatible structural changes to other classes, such as adding members or parents.

History

AOP has several direct antecedents A1 and A2:[1] reflection and metaobject protocols, subject-oriented programming, Composition Filters, and Adaptive Programming.[2]

Gregor Kiczales and colleagues at Xerox PARC developed the explicit concept of AOP and followed this with the AspectJ AOP extension to Java. IBM's research team pursued a tool approach over a language design approach and in 2001 proposed Hyper/J and the Concern Manipulation Environment, which have not seen wide use.

The examples in this article use AspectJ.

The Microsoft Transaction Server is considered to be the first major application of AOP followed by Enterprise JavaBeans.[3] [4]

Motivation and basic concepts

Typically, an aspect is scattered or tangled as code, making it harder to understand and maintain. It is scattered by the function (such as logging) being spread over a number of unrelated functions that might use its function, possibly in entirely unrelated systems or written in different languages. Thus, changing logging can require modifying all affected modules. Aspects become tangled not only with the mainline function of the systems in which they are expressed but also with each other. Changing one concern thus entails understanding all the tangled concerns or having some means by which the effect of changes can be inferred.

For example, consider a banking application with a conceptually very simple method for transferring an amount from one account to another:[5] void transfer(Account fromAcc, Account toAcc, int amount) throws Exception

However, this transfer method overlooks certain considerations that a deployed application would require, such as verifying that the current user is authorized to perform this operation, encapsulating database transactions to prevent accidental data loss, and logging the operation for diagnostic purposes.

A version with all those new concerns might look like this:

void transfer(Account fromAcc, Account toAcc, int amount, User user, Logger logger, Database database) throws Exception

In this example, other interests have become tangled with the basic functionality (sometimes called the business logic concern). Transactions, security, and logging all exemplify cross-cutting concerns.

Now consider what would happen if we suddenly need to change the security considerations for the application. In the program's current version, security-related operations appear scattered across numerous methods, and such a change would require major effort.

AOP tries to solve this problem by allowing the programmer to express cross-cutting concerns in stand-alone modules called aspects. Aspects can contain advice (code joined to specified points in the program) and inter-type declarations (structural members added to other classes). For example, a security module can include advice that performs a security check before accessing a bank account. The pointcut defines the times (join points) when one can access a bank account, and the code in the advice body defines how the security check is implemented. That way, both the check and the places can be maintained in one place. Further, a good pointcut can anticipate later program changes, so if another developer creates a new method to access the bank account, the advice will apply to the new method when it executes.

So for the example above implementing logging in an aspect:

aspect Logger

One can think of AOP as a debugging tool or a user-level tool. Advice should be reserved for cases in which one cannot get the function changed (user level)[6] or do not want to change the function in production code (debugging).

Join point models

The advice-related component of an aspect-oriented language defines a join point model (JPM). A JPM defines three things:

  1. When the advice can run. These are called join points because they are points in a running program where additional behavior can be usefully joined. A join point needs to be addressable and understandable by an ordinary programmer to be useful. It should also be stable across inconsequential program changes to maintain aspect stability. Many AOP implementations support method executions and field references as join points.
  2. A way to specify (or quantify) join points, called pointcuts. Pointcuts determine whether a given join point matches. Most useful pointcut languages use a syntax like the base language (for example, AspectJ uses Java signatures) and allow reuse through naming and combination.
  3. A means of specifying code to run at a join point. AspectJ calls this advice, and can run it before, after, and around join points. Some implementations also support defining a method in an aspect on another class.

Join-point models can be compared based on the join points exposed, how join points are specified, the operations permitted at the join points, and the structural enhancements that can be expressed.

AspectJ's join-point model

See main article: article and AspectJ.

Other potential join point models

There are other kinds of JPMs. All advice languages can be defined in terms of their JPM. For example, a hypothetical aspect language for UML may have the following JPM:

Inter-type declarations

Inter-type declarations provide a way to express cross-cutting concerns affecting the structure of modules. Also known as open classes and extension methods, this enables programmers to declare in one place members or parents of another class, typically to combine all the code related to a concern in one aspect. For example, if a programmer implemented the cross-cutting display-update concern using visitors, an inter-type declaration using the visitor pattern might look like this in AspectJ:

aspect DisplayUpdate

This code snippet adds the acceptVisitor method to the Point class.

Any structural additions are required to be compatible with the original class, so that clients of the existing class continue to operate, unless the AOP implementation can expect to control all clients at all times.

Implementation

AOP programs can affect other programs in two different ways, depending on the underlying languages and environments:

  1. a combined program is produced, valid in the original language and indistinguishable from an ordinary program to the ultimate interpreter
  2. the ultimate interpreter or environment is updated to understand and implement AOP features.

The difficulty of changing environments means most implementations produce compatible combination programs through a type of program transformation known as weaving. An aspect weaver reads the aspect-oriented code and generates appropriate object-oriented code with the aspects integrated. The same AOP language can be implemented through a variety of weaving methods, so the semantics of a language should never be understood in terms of the weaving implementation. Only the speed of an implementation and its ease of deployment are affected by the method of combination used.

Systems can implement source-level weaving using preprocessors (as C++ was implemented originally in CFront) that require access to program source files. However, Java's well-defined binary form enables bytecode weavers to work with any Java program in .class-file form. Bytecode weavers can be deployed during the build process or, if the weave model is per-class, during class loading. AspectJ started with source-level weaving in 2001, delivered a per-class bytecode weaver in 2002, and offered advanced load-time support after the integration of AspectWerkz in 2005.

Any solution that combines programs at runtime must provide views that segregate them properly to maintain the programmer's segregated model. Java's bytecode support for multiple source files enables any debugger to step through a properly woven .class file in a source editor. However, some third-party decompilers cannot process woven code because they expect code produced by Javac rather than all supported bytecode forms (see also § Criticism, below).

Deploy-time weaving offers another approach.[7] This basically implies post-processing, but rather than patching the generated code, this weaving approach subclasses existing classes so that the modifications are introduced by method-overriding. The existing classes remain untouched, even at runtime, and all existing tools, such as debuggers and profilers, can be used during development. A similar approach has already proven itself in the implementation of many Java EE application servers, such as IBM's WebSphere.

Terminology

Standard terminology used in Aspect-oriented programming may include:

Cross-cutting concerns:

See main article: article and Cross-cutting concern. Even though most classes in an object-oriented model will perform a single, specific function, they often share common, secondary requirements with other classes. For example, we may want to add logging to classes within the data-access layer and also to classes in the UI layer whenever a thread enters or exits a method. Further concerns can be related to security such as access control[8] or information flow control.[9] Even though each class has a very different primary functionality, the code needed to perform the secondary functionality is often identical.

Advice:

See main article: article and Advice (programming). This is the additional code that you want to apply to your existing model. In our example, this is the logging code that we want to apply whenever the thread enters or exits a method.:

Pointcut:

See main article: article and Pointcut. This refers to the point of execution in the application at which cross-cutting concern needs to be applied. In our example, a pointcut is reached when the thread enters a method, and another pointcut is reached when the thread exits the method.

Aspect:

See main article: article and Aspect (computer science). The combination of the pointcut and the advice is termed an aspect. In the example above, we add a logging aspect to our application by defining a pointcut and giving the correct advice.

Comparison to other programming paradigms

Aspects emerged from object-oriented programming and reflective programming. AOP languages have functionality similar to, but more restricted than, metaobject protocols. Aspects relate closely to programming concepts like subjects, mixins, and delegation. Other ways to use aspect-oriented programming paradigms include Composition Filters and the hyperslices approach. Since at least the 1970s, developers have been using forms of interception and dispatch-patching that resemble some of the implementation methods for AOP, but these never had the semantics that the cross-cutting specifications provide in one place.

Designers have considered alternative ways to achieve separation of code, such as C#'s partial types, but such approaches lack a quantification mechanism that allows reaching several join points of the code with one declarative statement.

Though it may seem unrelated, in testing, the use of mocks or stubs requires the use of AOP techniques, such as around advice. Here the collaborating objects are for the purpose of the test, a cross-cutting concern. Thus, the various Mock Object frameworks provide these features. For example, a process invokes a service to get a balance amount. In the test of the process, it is unimportant where the amount comes from, but only that the process uses the balance according to the requirements.

Adoption issues

Programmers need to be able to read and understand code to prevent errors.[10] Even with proper education, understanding cross-cutting concerns can be difficult without proper support for visualizing both static structure and the dynamic flow of a program. Starting in 2002, AspectJ began to provide IDE plug-ins to support the visualizing of cross-cutting concerns. Those features, as well as aspect code assist and refactoring, are now common.

Given the power of AOP, making a logical mistake in expressing cross-cutting can lead to widespread program failure. Conversely, another programmer may change the join points in a program, such as by renaming or moving methods, in ways that the aspect writer did not anticipate and with unforeseen consequences. One advantage of modularizing cross-cutting concerns is enabling one programmer to easily affect the entire system. As a result, such problems manifest as a conflict over responsibility between two or more developers for a given failure. AOP can expedite solving these problems, as only the aspect must be changed. Without AOP, the corresponding problems can be much more spread out.

Criticism

The most basic criticism of the effect of AOP is that control flow is obscured, and that it is not only worse than the much-maligned GOTO statement, but is closely analogous to the joke COME FROM statement. The obliviousness of application, which is fundamental to many definitions of AOP (the code in question has no indication that an advice will be applied, which is specified instead in the pointcut), means that the advice is not visible, in contrast to an explicit method call.[11] [12] For example, compare the COME FROM program:[11] 5 INPUT X10 PRINT 'Result is :'15 PRINT X20 COME FROM 1025 X = X * X30 RETURNwith an AOP fragment with analogous semantics:main input result(int x) around(int x): call(result(int)) && args(x) Indeed, the pointcut may depend on runtime condition and thus not be statically deterministic. This can be mitigated but not solved by static analysis and IDE support showing which advices potentially match.

General criticisms are that AOP purports to improve "both modularity and the structure of code", but some counter that it instead undermines these goals and impedes "independent development and understandability of programs".[13] Specifically, quantification by pointcuts breaks modularity: "one must, in general, have whole-program knowledge to reason about the dynamic execution of an aspect-oriented program."[14] Further, while its goals (modularizing cross-cutting concerns) are well understood, its actual definition is unclear and not clearly distinguished from other well-established techniques.[13] Cross-cutting concerns potentially cross-cut each other, requiring some resolution mechanism, such as ordering.[13] Indeed, aspects can apply to themselves, leading to problems such as the liar paradox.[15]

Technical criticisms include that the quantification of pointcuts (defining where advices are executed) is "extremely sensitive to changes in the program", which is known as the fragile pointcut problem.[13] The problems with pointcuts are deemed intractable. If one replaces the quantification of pointcuts with explicit annotations, one obtains attribute-oriented programming instead, which is simply an explicit subroutine call and suffers the identical problem of scattering, which AOP was designed to solve.[13]

Implementations

Many programming languages have implemented AOP, within the language, or as an external library, including:

See also

Further reading

External links

Notes and References

  1. 10.1007/BFb0053381 . Aspect-oriented programming . Proceedings of the 11th European Conference on Object-Oriented Programming . ECOOP'97 . 1241 . 220–242 . Lecture Notes in Computer Science (LNCS) . 1997 . Kiczales . G. . Gregor Kiczales . Lamping . J. . Mendhekar . A. . Maeda . C. . Lopes . C. . Loingtier . J. M. . Irwin . J. . 3-540-63089-9 . 10.1.1.115.8660 . live . https://web.archive.org/web/20160112141810/http://www.cs.ubc.ca/%7Egregor/papers/kiczales-ECOOP1997-AOP.pdf . 2016-01-12.
  2. "Adaptive Object Oriented Programming: The Demeter Approach with Propagation Patterns" Karl Liebherr 1996 presents a well-worked version of essentially the same thing (Lieberherr subsequently recognized this and reframed his approach).
  3. Book: Don Box. Chris Sells. Essential.NET: The common language runtime. registration. 4 October 2011. 4 November 2002. Addison-Wesley Professional. 978-0-201-73411-9. 206.
  4. Book: Roman. Ed. Sriganesh. Rima Patel. Brose. Gerald. Mastering Enterprise JavaBeans. 4 October 2011. 1 January 2005. John Wiley and Sons. 978-0-7645-8492-3. 285.
  5. Note: The examples in this article appear in a syntax that resembles that of the Java language.
  6. Web site: gnu.org. GNU Project. 5 May 2018. live. https://web.archive.org/web/20171224053656/http://www.gnu.org/software/emacs/manual/html_node/elisp/Advising-Functions.html. 24 December 2017.
  7. Web site: Archived copy . 2005-06-19 . dead . https://web.archive.org/web/20051008065854/http://www.forum2.org/tal/AspectJ2EE.pdf . 2005-10-08.
  8. B. De Win, B. Vanhaute and B. De Decker. "Security through aspect-oriented programming". In Advances in Network and Distributed Systems Security (2002).
  9. T. Pasquier, J. Bacon and B. Shand. "FlowR: Aspect Oriented Programming for Information Flow Control in Ruby". In ACM Proceedings of the 13th international conference on Modularity (Aspect Oriented Software Development) (2014).
  10. [Edsger Dijkstra]
  11. AOP Considered Harmful . Constantinos . Constantinides . Therapon . Skotiniotis . Maximilian . Störzer. September 2004. 5 May 2018. live. https://web.archive.org/web/20160323061458/https://pp.info.uni-karlsruhe.de/uploads/publikationen/constantinides04eiwas.pdf. 23 March 2016. European Interactive Workshop on Aspects in Software (EIWAS) . Berlin, Germany.
  12. [C2:ComeFrom]
  13. 10.1145/1167515.1167514 . The paradoxical success of aspect-oriented programming . ACM SIGPLAN Notices . 41 . 10 . 481–497 . 2006 . Steimann . F. . 10.1.1.457.2210., (slides,slides 2, abstract), Friedrich Steimann, Gary T. Leavens, OOPSLA 2006
  14. Web site: More Modular Reasoning for Aspect-Oriented Programs. 11 August 2015. live. https://web.archive.org/web/20150812045258/http://www.eecs.ucf.edu/~leavens/modular-aop/. 12 August 2015.
  15. Web site: AOP and the Antinomy of the Liar. fernuni-hagen.de. 5 May 2018. live. https://web.archive.org/web/20170809201001/http://www.fernuni-hagen.de/ps/pubs/FOAL2006.pdf. 9 August 2017.
  16. Numerous:Afterthought, LOOM.NET, Enterprise Library 3.0 Policy Injection Application Block, AspectDNG, DynamicProxy, Compose*, PostSharp, Seasar.NET, DotSpect (.SPECT), Spring.NET (as part of its functionality), Wicca and Phx.Morph, SetPoint
  17. Web site: Welcome to as3-commons-bytecode. as3commons.org. 5 May 2018. live. https://web.archive.org/web/20141003100345/http://www.as3commons.org/as3-commons-bytecode/. 3 October 2014.
  18. Web site: Ada2012 Rationale. adacore.com. 5 May 2018. live. https://web.archive.org/web/20160418132340/http://www.adacore.com/uploads/technical-papers/Ada2012_Rational_Introducion.pdf. 18 April 2016.
  19. Web site: Function Hooks. https://archive.today/20130117125117/http://www.autohotkey.com/forum/viewtopic.php?p=243426. dead. 17 January 2013. autohotkey.com. 5 May 2018.
  20. Several: AspectC++, FeatureC++, AspectC, AspeCt-oriented C, Aspicere
  21. Web site: Cobble. vub.ac.be. 5 May 2018.
  22. Web site: AspectCocoa. neu.edu. 5 May 2018. dead. https://web.archive.org/web/20071026022525/http://www.ood.neu.edu/aspectcocoa/. 26 October 2007.
  23. Web site: ColdSpring Framework: Welcome. 5 November 2005. 5 May 2018. bot: unknown. https://web.archive.org/web/20051105014513/http://coldspringframework.org/. 5 November 2005.
  24. Web site: Closer Project: AspectL.. 11 August 2015. live. http://archive.wikiwix.com/cache/20110223172923/http://common-lisp.net/project/closer/aspectl.html. 23 February 2011.
  25. Web site: infra – Frameworks Integrados para Delphi – Google Project Hosting. 11 August 2015. live. https://web.archive.org/web/20150909070130/http://code.google.com/p/infra/. 9 September 2015.
  26. Web site: meaop – MeSDK: MeObjects, MeRTTI, MeAOP – Delphi AOP(Aspect Oriented Programming), MeRemote, MeService... – Google Project Hosting. 11 August 2015. live. https://web.archive.org/web/20150910210536/http://code.google.com/p/meaop/. 10 September 2015.
  27. Web site: Google Project Hosting. 11 August 2015. live. https://web.archive.org/web/20141225080131/https://code.google.com/p/delphisorcery/. 25 December 2014.
  28. Web site: RemObjects Cirrus. codegear.com. 5 May 2018. dead. https://web.archive.org/web/20120123094027/http://prismwiki.codegear.com/en/Cirrus. 23 January 2012.
  29. Web site: Emacs Advice Functions. GNU Project. 5 May 2018. live. https://web.archive.org/web/20111024211408/http://www.gnu.org/software/emacs/elisp/html_node/Advising-Functions.html. 24 October 2011.
  30. [Monad (functional programming)|Monad]
  31. Numerous others: CaesarJ, Compose*, Dynaop, JAC, Google Guice (as part of its functionality), Javassist, JAsCo (and AWED), JAML, JBoss AOP, LogicAJ, Object Teams, PROSE, The AspectBench Compiler for AspectJ (abc), Spring framework (as part of its functionality), Seasar, The JMangler Project, InjectJ, GluonJ, Steamloom
  32. Many: Advisable, Ajaxpect, jQuery AOP Plugin, Aspectes, AspectJS, Cerny.js, Dojo Toolkit, Humax Web Framework, Joose, PrototypePrototype Function#wrap, YUI 3 (Y.Do)
  33. Using built-in support for categories (which allows the encapsulation of aspect code) and event-driven programming (which allows the definition of before and after event handlers).
  34. Web site: AspectLua. 11 August 2015. live. https://web.archive.org/web/20150717094121/http://luaforge.net/projects/aspectlua/. 17 July 2015.
  35. Web site: MAKAO, re(verse)-engineering build systems. https://archive.today/20120724151524/http://www.bramadams.org/makao/. dead. 24 July 2012. 11 August 2015.
  36. Web site: McLab. 11 August 2015. live. https://web.archive.org/web/20150924093214/http://www.sable.mcgill.ca/mclab/aspectmatlab/. 24 September 2015.
  37. Web site: AspectML – Aspect-oriented Functional Programming Language Research . dead . https://web.archive.org/web/20101205005108/http://www.cs.princeton.edu/sip/projects/aspectml/ . 5 December 2010 . 11 August 2015.
  38. Web site: nemerle/README.md at master · rsdn/nemerle. . 22 March 2018.
  39. Web site: Aspect – Aspect-Oriented Programming (AOP) for Perl – metacpan.org. Adam Kennedy. 11 August 2015. live. https://web.archive.org/web/20130831064935/https://metacpan.org/module/Aspect. 31 August 2013.
  40. Several: PHP-AOP (AOP.io), Go! AOP framework, PHPaspect, Seasar.PHP, PHP-AOP, Flow, AOP PECL Extension
  41. Web site: 14 December 2005 . Aspect-Oriented Programming in Prolog . dead . https://web.archive.org/web/20120303120515/https://www.bigzaphod.org/whirl/dma/docs/aspects/aspects-man.html . 3 March 2012 . 5 May 2018 . bigzaphod.org.
  42. Several: PEAK, Aspyct AOP, Lightweight Python AOP, Logilab's aspect module, Pythius, Spring Python's AOP module, Pytilities' AOP module, aspectlib
  43. Web site: PLaneT Package Repository : PLaneT > dutchyn > aspectscheme.plt. 11 August 2015. live. https://web.archive.org/web/20150905062740/http://planet.racket-lang.org/display.ss?package=aspectscheme.plt&owner=dutchyn. 5 September 2015.
  44. Web site: AspectR – Simple aspect-oriented programming in Ruby. 11 August 2015. live. http://archive.wikiwix.com/cache/20150812003432/http://aspectr-fork.sourceforge.net/. 12 August 2015.
  45. Web site: Home. https://web.archive.org/web/20071026055811/http://aquarium.rubyforge.org/. dead. 26 October 2007. Dean Wampler. 11 August 2015.
  46. Web site: gcao/aspector. GitHub. 11 August 2015. live. https://web.archive.org/web/20150104180534/https://github.com/gcao/aspector. 4 January 2015.
  47. Web site: AspectS. tu-ilmenau.de. 5 May 2018. dead. https://web.archive.org/web/20060106112030/http://www.prakinf.tu-ilmenau.de/~hirsch/Projects/Squeak/AspectS/. 6 January 2006.
  48. Web site: MetaclassTalk: Reflection and Meta-Programming in Smalltalk. 11 August 2015. dead. https://web.archive.org/web/20150729062351/http://csl.ensm-douai.fr/MetaclassTalk. 29 July 2015.
  49. Web site: WEAVR. iit.edu. 5 May 2018. live. https://web.archive.org/web/20081212200221/http://www.iit.edu/~concur/weavr/. 12 December 2008.
  50. Web site: aspectxml – An Aspect-Oriented XML Weaving Engine (AXLE) – Google Project Hosting. 11 August 2015. live. https://web.archive.org/web/20150912161613/http://code.google.com/p/aspectxml/. 12 September 2015.