270

I understand object oriented programming, and have been writing OO programs for a long time. People seem to talk about aspect-oriented programming, but I've never really learned what it is or how to use it. What is the basic paradigm?

This question is related, but doesn't quite ask it:

Aspect-Oriented Programming vs. Object Oriented Programming

Community
  • 1
  • 1
Sophie
  • 2,957
  • 3
  • 18
  • 14
  • 9
    IMAO, the link provided in the question has clearer and thorough answer than the accepted one here. People reading this question might read it first. – David Chen Nov 14 '17 at 18:16

7 Answers7

231

AOP addresses the problem of cross-cutting concerns, which would be any kind of code that is repeated in different methods and can't normally be completely refactored into its own module, like with logging or verification. So, with AOP you can leave that stuff out of the main code and define it vertically like so:

function mainProgram()
{ 
   var x =  foo();
   doSomethingWith(x);
   return x;
}

aspect logging
{ 
    before (mainProgram is called):
    { 
       log.Write("entering mainProgram");
    }

    after (mainProgram is called):
    { 
       log.Write(  "exiting mainProgram with return value of "
                  + mainProgram.returnValue);
    }
 } 

aspect verification
{ 
    before (doSomethingWith is called):
    { 
       if (doSomethingWith.arguments[0] == null) 
       { 
          throw NullArgumentException();
       }

       if (!doSomethingWith.caller.isAuthenticated)
       { 
          throw Securityexception();
       }
    }
 }

And then an aspect-weaver is used to compile the code into this:

function mainProgram()
{ 
   log.Write("entering mainProgram");

   var x = foo();   

   if (x == null) throw NullArgumentException();
   if (!mainProgramIsAuthenticated()) throw Securityexception();
   doSomethingWith(x);   

   log.Write("exiting mainProgram with return value of "+ x);
   return x;
} 
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
  • 18
    Do you need language support for this, then? What language is your example in? – Sophie Oct 28 '08 at 03:51
  • 11
    This is pseudocode but the most well-known example is AspectJ, which is an AOP modification of Java, which uses a similar technique called cutpoints. – Mark Cidade Oct 28 '08 at 03:55
  • Kind of like a Other or ETC class then? Or is because you're just using a very simplified example? – melaos Dec 31 '08 at 02:10
  • I wouldn't call logging and verification "miscellaneous" concerns. Although you could have a "Misc" or "Util" aspect but that would be kinda sloppy. – Mark Cidade Jan 01 '09 at 15:48
  • 82
    Voodoo. And I thought OOP was overkill. – Aiden Bell May 11 '09 at 20:56
  • 19
    Mark, is this like decorating a method's entry and exit points? – Filip Dupanović Mar 14 '11 at 10:05
  • 2
    @Filip if it's for the purpose of intercepting or inserting code at those points then that can be considered AOP. – Mark Cidade Mar 14 '11 at 19:03
  • 4
    @AidenBell If unseen action at a distance can be considered voodoo, then yes, it's voodoo. Under Moose metaprogamming, [method modifiers](http://search.cpan.org/~ether/Moose-2.1605/lib/Moose/Manual/MethodModifiers.pod) like *before, after, around, inner, augment* do just exactly that. It obscures the program's execution flow. These can be almost impossible to trace, especially when they derive from that system's version of aspects, which it calls [roles](http://search.cpan.org/~ether/Moose-2.1605/lib/Moose/Manual/Roles.pod). One can compose systems of staggering complexity with all this. – tchrist Mar 19 '16 at 23:03
  • Are there any similarities between AOP and Singleton pattern? – Harsha Jayamanna Dec 06 '16 at 14:45
  • 2
    @Harshakj89: no, they are two unrelated concepts – Mark Cidade Dec 06 '16 at 15:00
  • @MarkCidade I have an understanding about AOP, but i'm still learning Singleton pattern. I'll be able to figure out differences when going forward. Thanks. – Harsha Jayamanna Dec 06 '16 at 15:05
  • @MarkCidade, I need some help understanding the real world scenarios where AOP is helpful. The examples I've seen mostly talked about logging and tracing, which makes sense to me. Can you point to me some use cases other than that? I'm not clear on where it should be used otherwise. Also, given the performance penalty of creating a proxy, are they used in production? Sorry, if my question is too naive. – chandra_cst Jun 13 '17 at 20:20
  • As fars as I know, proxies are used in production. Another use case includes transactions. You may not want to pepper your code everywhere with transaction-related code. Instead you can use an transaction aspect in AOP and only put code for that concern there, which is then weaved into the methods to which you want to apply it. – Mark Cidade Jun 13 '17 at 20:23
  • It seems to me like this concept is very similar to, for example, Flask or Django decorators. Can anybody confirm this? – belvederef Dec 12 '18 at 11:58
  • In many apps which support plugins, each plugin is essentially an aspect and the plugin system achieves the same goals as AOP. The only difference is that plugins hook into the app via its own plugin system, which is written in the base programming language, rather than using AOP extensions and all of the extreme pitfalls/open-endedness that come with AOP. – Andy Jan 05 '19 at 02:07
  • It seems like we ought to be able to address these cross-cutting concerns using our existing OO language constructs or with metaprogramming. Would such an approach be considered AOP though? And why the need for a separate paradigm? – ibrust Dec 03 '22 at 13:46
  • AOP for golang: https://github.com/gogap/aop – frostcs Dec 30 '22 at 21:54
13

Unfortunately, it seems to be surprisingly difficult to make AOP really useful in a normal mid-large size organization. (Editor support, sense of control, the fact that you start with the not-so-important things leading to code-rot, people going home to their families, etc.)

I put my hopes to composite oriented programming, which is something more and more realistic. It connects to many popular ideas and gives you something really cool.

Look at an up and coming implementation here: qi4j.org/

PS. Actually, I think that one of the beauties with AOP is also its achilles heel: Its non-intrusive, letting people ignore it if they can, so it will be treated as a secondary concern in most organizations.

Steven Evers
  • 16,649
  • 19
  • 79
  • 126
Hugo
  • 4,004
  • 1
  • 31
  • 33
12

Copied from Spring in Action

AOP is often defined as a technique that promotes separation of concerns in a software system. Systems are composed of several components, each responsible for a specific piece of functionality. But often these components also carry additional responsibilities beyond their core functionality. System services such as logging, transaction management, and security often find their way into components whose core responsibilities is something else. These system services are commonly referred to as cross-cutting concerns because they tend to cut across multiple components in a system.

9

Copied from a duplicate for completeness (Einstein):

The classic examples are security and logging. Instead of writing code within your application to log occurance of x or check object z for security access control there is a language contraption "out of band" of normal code which can systematically inject security or logging into routines that don't nativly have them in such a way that even though your code doesn't supply it -- its taken care of.

A more concrete example is the operating system providing access controls to a file. A software program does not need to check for access restrictions because the underlying system does that work for it.

If you think you need AOP in my experience you actually really need to be investing more time and effort into appropriate meta-data management within your system with a focus on well thought structural / systems design.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
7

Copied from a duplicate for completeness (Buzzer):

Class and method attributes in .NET are a form of aspect-oriented programming. You decorate your classes/methods with attributes. Behind the scenes this adds code to your class/method that performs the particular functions of the attribute. For example, marking a class serializable allows it to be serialized automatically for storage or transmission to another system. Other attributes might mark certain properties as non-serializable and these would be automatically omitted from the serialized object. Serialization is an aspect, implemented by other code in the system, and applied to your class by the application of a "configuration" attribute (decoration) .

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
5

There is an example of AOP, it used spring AOP as an example. The example is quite easy to understand.

Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.

Reference: http://www.mkyong.com/spring/spring-aop-examples-advice/

R.F
  • 335
  • 3
  • 8
  • In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. – R.F Nov 10 '17 at 12:23
4

AOP is a way to better modularize your application for functionality that spans across multiple boundaries. AOP is another way to encapsulate these features and follow Single Responsiblity by moving these cross-cutting concerns (logging, error handling, etc.) out of the main components of your application. When used appropriately AOP can lead to higher levels of maintainability and extensibility in your application over time.

SaaS Developer
  • 9,835
  • 7
  • 34
  • 45