281

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

1
  • 12
    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. Commented Nov 14, 2017 at 18:16

9 Answers 9

245

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;
} 
Sign up to request clarification or add additional context in comments.

17 Comments

Do you need language support for this, then? What language is your example in?
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.
Voodoo. And I thought OOP was overkill.
Mark, is this like decorating a method's entry and exit points?
@AidenBell If unseen action at a distance can be considered voodoo, then yes, it's voodoo. Under Moose metaprogamming, method modifiers 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. One can compose systems of staggering complexity with all this.
|
14

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.

Comments

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.

Comments

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.

Comments

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) .

Comments

6

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/

1 Comment

In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns.
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.

Comments

4

Analogy: Imagine you are building a big and complicated home. In programming paradigm like OOPS, we have different rooms(classes) each with different functionalities(methods) and stuff(data). Now we found out we have security risk in our home. So we create a master plan ie to install CCTV camera to every room of our home. In OOPS, we go to each room, and install CCTV camera in the entrance of the room. Its like doing same task over and over again for every room. But in AOPs, we dont need to do same task over and over again. Instead it allow us to create a plan(called aspects) for installing CCTV and the plan can be weaved in all the room at once. We just need to focus on main design and AOP takes care of adding security cameras wherever we need.

So the key terminologies of AOP are:

  1. Concerns (or cross cutting concerns)

    • These are functionalities that has to be added across multiple parts of program.
    • Example: Security, logging or error handling
    • In our analogy, our concern is the security risk
  2. Aspects

    • It is like master plan for dealing with concern. It encapsulate cross cutting concerns in a modular unit.
    • In our analogy, our plan to install CCTV in every room is aspects
  3. Join points

    • It is the specific points on our program where we want to apply the code
    • In our analogy , we were installing cctv in the room's entrance
  4. Advice

    • Advice is the actual code that implements our cross cutting concern and it is defined in join points

Another example from which you can understand it easily

Let's say we have to print 'Hello Worlds' to the console. Now we want to log every time this message is printed. In traditional methods like OOPs, we'd go to print statement and add log line (like Console.log("message)). But in AOP, we create an aspect that says "Every time there is print statement, also log it" . We don't touch the original print statement; we just apply our aspect and voila ! Logging is added without changing core code.

Merits:

  • We can keep our code clean and concerns are neatly separated
  • Changing one concern doesn't affect whole program
  • Aspect can be reused in different parts of the programs

Demerits:

  • Hard to learn
  • Complex to debug

1 Comment

Hey, your explanation is so goooood. :) very easy to understand concept and purpose in behind. You should be a lecture.
0

Our goal in Aspect Oriented Programming is to reduce the amount of boilerplate code.

Let's give an example, we have a service, and in this service, let's first print the service.start() log, then the service transaction log, and finally the standard log.

Our 1.log process and 3.log process are the same under the package, so we can reduce boirplate code writing by using it as Cross Cutting.

What is Aspect Oriented Programming?

AOP is an approach that helps reduce the complexity of the software and increase modularity. The purpose of modularization here is to separate the non-functional code, that is, the intersecting interests, used in many parts of the system during the application, into small pieces (Separation of Cross Cutting Concerns).In this way, the structures that will be used throughout the application are abstracted from the system and encapsulated. It allows it to be used in many places. In general, it can be said that AOP helps to make the existing system better rather than solving a problem.

At this point, we can perform common operations and reduction operations here.

What are the benefits of AOP?

  • Our application is more flexible and easy to manage,
  • Getting rid of repetitive code patterns,
  • A cleaner and more understandable code,
  • Separation from core logic and intersections.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.