computing
Computing is any goal-oriented activity requiring, benefiting from, or creating computer, computing machinery. It includes the study and experimentation of algorithmic processes, and the development of both computer hardware, hardware and softw ...
, aspect-oriented programming (AOP) is a
programming paradigm
A programming paradigm is a relatively high-level way to conceptualize and structure the implementation of a computer program. A programming language can be classified as supporting one or more paradigms.
Paradigms are separated along and descri ...
that aims to increase
modularity
Modularity is the degree to which a system's components may be separated and recombined, often with the benefit of flexibility and variety in use. The concept of modularity is used primarily to reduce complexity by breaking a system into varying ...
by allowing the separation ofcross-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
In computer software, business logic or domain logic is the part of the program that encodes the real-world business rules that determine how data can be created, stored, and changed. It is contrasted with the remainder of the software that might ...
(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
Logging is the process of cutting, processing, and moving trees to a location for transport. It may include skidder, skidding, on-site processing, and loading of trees or trunk (botany), logs onto logging truck, trucksAspectJ 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.
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:
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) 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:
# 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.
# 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.
# 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
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:
* Join points are all model elements.
* Pointcuts are some
Boolean expression
In computer science, a Boolean expression (also known as logical expression) is an expression used in programming languages that produces a Boolean value when evaluated. A Boolean value is either true or false. A Boolean expression may be compos ...
combining the model elements.
* The means of affect at these points are a visualization of all the matched join points.
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:
# a combined program is produced, valid in the original language and indistinguishable from an ordinary program to the ultimate interpreter
# 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
A program transformation is any operation that takes a computer program and generates another program. In many cases the transformed program is required to be semantically equivalent to the original, relative to a particular Formal semantics of p ...
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. 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
International Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American Multinational corporation, multinational technology company headquartered in Armonk, New York, and present in over 175 countries. It is ...
Standard terminology used in Aspect-oriented programming may include:
;Cross-cutting concerns: 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
In physical security and information security, access control (AC) is the action of deciding whether a subject should be granted or denied access to an object (for example, a place or a resource). The act of ''accessing'' may mean consuming ...
B. De Win, B. Vanhaute and B. De Decker. "Security through aspect-oriented programming". In ''Advances in Network and Distributed Systems Security'' (2002). or information flow control.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). Even though each class has a very different primary functionality, the code needed to perform the secondary functionality is often identical.
;
;Advice: 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: 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: 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
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
and
reflective programming
In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.
Historical background
The earliest computers were programmed in their native assembly lang ...
. 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.
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. For example, compare the COME FROM program:
5 INPUT X
10 PRINT 'Result is :'
15 PRINT X
20 COME FROM 10
25 X = X * X
30 RETURN
with 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"., slides slides 2
), Friedrich Steimann, Gary T. Leavens, OOPSLA 2006 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." 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. Cross-cutting concerns potentially cross-cut each other, requiring some resolution mechanism, such as ordering. Indeed, aspects can apply to themselves, leading to problems such as the liar paradox.
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''. 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.
Implementations
Many
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s have implemented AOP, within the language, or as an external
library
A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
, including:
*
.NET
The .NET platform (pronounced as "''dot net"'') is a free and open-source, managed code, managed computer software framework for Microsoft Windows, Windows, Linux, and macOS operating systems. The project is mainly developed by Microsoft emplo ...
framework languages ( C#, Visual Basic (.NET) (VB.NET))
PostSharp is a commercial AOP implementation with a free but limited edition.
** Unity provides an API to facilitate proven practices in core areas of programming including data access, security, logging, exception handling and others.
AspectDN is an AOP implementation allowing to weave the aspects directly on the .NET executable files.
*
ActionScript
ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (mean ...
COBOL
COBOL (; an acronym for "common business-oriented language") is a compiled English-like computer programming language designed for business use. It is an imperative, procedural, and, since 2002, object-oriented language. COBOL is primarily ...
Objective-C
Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was ...
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
*
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), was an ancient sacred precinct and the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient Classical antiquity, classical world. The A ...
Emacs Lisp
Emacs Lisp is a Lisp dialect made for Emacs.
It is used for implementing most of the editing functionality built into Emacs, the remainder being written in C, as is the Lisp interpreter.
Emacs Lisp code is used to modify, extend and customi ...
*
Groovy
''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1960s and 1970s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context.
History
The word ...
*
Haskell
Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
*
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
JavaScript
JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.
Web browsers have ...
Matlab
MATLAB (an abbreviation of "MATrix LABoratory") is a proprietary multi-paradigm programming language and numeric computing environment developed by MathWorks. MATLAB allows matrix manipulations, plotting of functions and data, implementat ...
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
Prolog
Prolog is a logic programming language that has its origins in artificial intelligence, automated theorem proving, and computational linguistics.
Prolog has its roots in first-order logic, a formal logic. Unlike many other programming language ...
Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
*
Squeak
Squeak is an object-oriented, class-based, and reflective programming language. It was derived from Smalltalk-80 by a group that included some of Smalltalk-80's original developers, initially at Apple Computer, then at Walt Disney Imaginee ...
Smalltalk
Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
XML
Extensible Markup Language (XML) is a markup language and file format for storing, transmitting, and reconstructing data. It defines a set of rules for encoding electronic document, documents in a format that is both human-readable and Machine-r ...
functional programming
In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declarat ...
languages
*
Programming paradigm
A programming paradigm is a relatively high-level way to conceptualize and structure the implementation of a computer program. A programming language can be classified as supporting one or more paradigms.
Paradigms are separated along and descri ...
Executable UML Executable UML (xtUML or xUML) is both a software development method and a highly abstract software language. It was described for the first time in 2002 in the book "Executable UML: A Foundation for Model-Driven Architecture". The language "combine ...