Architecture & DesignAspect Oriented Programming

Aspect Oriented Programming

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Aspect Oriented Programming (AOP) is a promising new technology for separating crosscutting concerns that are usually hard to do in object-oriented programming. This article aims to be an introductory point to the basic concepts associated with this new paradigm.

Object Oriented Programming

Nowadays, object-oriented programming (OOP) has become the mainstream programming paradigm where real world problems are decomposed into objects that abstract behavior and data in a single unit.

OOP encourages software re-use by providing design and language constructs for modularity, encapsulation, inheritance, and polymorphism. Although OOP has met great success in modeling and implementing complex software systems, it has its problems. Practical experience with large projects has shown that programmers may face some problems with maintaining their code because it becomes increasingly difficult to cleanly separate concerns into modules. An attempt to do a minor change in the program design may require several updates to a large number of unrelated modules.

Crosscutting Concerns

An example of crosscutting concerns is “logging,” which is frequently used in distributed applications to aid debugging by tracing method calls. Suppose we do logging at both the beginning and the end of each function body. This will result in crosscutting all classes that have at least one function. Other typical crosscutting concerns include context-sensitive error handling, performance optimization, and design patterns.

Crosscutting concerns may exist in some programs, especially large ones. However, in some situations, redesign of the system might transform a crosscutting into an object. AOP assumes that crosscutting concerns may exist in programs and can’t be re-factored out of the design in all situations.

Aspect Oriented Programming

AOP is a new technology for separating crosscutting concerns into single units called aspects. An aspect is a modular unit of crosscutting implementation. It encapsulates behaviors that affect multiple classes into reusable modules. With AOP, we start by implementing our project using our OO language (for example, Java), and then we deal separately with crosscutting concerns in our code by implementing aspects. Finally, both the code and aspects are combined into a final executable form using an aspect weaver. As a result, a single aspect can contribute to the implementation of a number of methods, modules, or objects, increasing both reusability and maintainability of the code. Figure 1 explains the weaving process. You should note that the original code doesn’t need to know about any functionality the aspect has added; it needs only to be recompiled without the aspect to regain the original functionality.

Figure 1: Aspect Weaver

In that way, AOP complements object-oriented programming, not replacing it, by facilitating another type of modularity that pulls together the widespread implementation of a crosscutting concern into a single unit. These units are termed aspects, hence the name aspect oriented programming.

Aspect Oriented Programming and Java

AOP is a concept, so it is not bound to a specific programming language. In fact, it can help with the shortcomings of all languages (not only OO languages) that use single, hierarchical decomposition. AOP has been implemented in different languages (for example, C++, Smalltalk, C#, C, and Java).

Of course, the language that gains a great interest of the research community is the Java language. The following is a list of tools that support AOP with Java:

AspectJ, created at Xerox PARC, was proposed as an extension of the Java language for AOP. The rest of this article is related to AspectJ terminology.

Join points, Pointcut, Advice, and Introduction

Where the tools of OOP are inheritance, encapsulation, and polymorphism, the components of AOP are join points, pointcut, advice, and introduction. For a better understanding of these new terms, let’s consider the following simple example.

public class TestClass {
  public void sayHello () {
    System.out.println ("Hello, AOP");
  }

  public void sayAnyThing (String s) {
    System.out.println (s);
  }

  public static void main (String[] args) {
    sayHello ();
    sayAnyThing ("ok");
  }
}

Listing 1: TestClass.java

Now, we have our existing Java code in TestClass.java. Let’s assume that we want to use aspects to do the following modifications:

  1. We would like to print a message before and after any call to the TestClass.sayHello() method.
  2. We need to test that the argument of the TestClass.sayAnyThing() method is at least three characters.

The following list is the AspectJ implementation.

1: public aspect MyAspect {
2:   public pointcut sayMethodCall (): call (public void
                                             TestClass.say*() );
3:   public pointcut sayMethodCallArg (String str): call
                     (public void TestClass.sayAnyThing (String))
                     && args(str);

4:   before(): sayMethodCall() {
5:   System.out.println("n TestClass." +
       thisJoinPointStaticPart.getSignature().getName() +
       "start..." );
6:   }

7:   after(): sayMethodCall() {
8:   System.out.println("n TestClass." +
       thisJoinPointStaticPart.getSignature().getName() +
       " end...");
9:   }

10:   before(String str): sayMethodCallArg(str) {
11:     if (str .length() < 3) {
12:     System.out.println ("Error: I can't say words less than 3
                             characters");
13:     return;
14:     }
15:   }
16: }

Listing 2: MyAspect.aj

Line 1 defines an aspect in the same way we define a Java class. Like any Java class, an aspect may have member variables and methods. In addition, it may include pointcuts, advices, and introductions.

In Lines 2 and 3, we specify where in the TestClass code our modification will take place. In AspectJ terms, we define two pointcuts. To explain what a pointcut means, we first need to define join points.

Join points represent well-defined points in a program’s execution. Typical join points in AspectJ include method/constructor calls, method/constructor execution, field get and set, exception handler execution, and static and dynamic initialization. In our example, we have two join points: the call to TestClass.sayHello and TestClass.sayAnyThing methods.

Pointcut is a language construct that picks out a set of join points based on defined criteria. The criteria can be explicit function names, or function names specified by wildcards.

public pointcut sayMethodCall (): call (public void
                                        TestClass.say*() );

In the preceding line, we define a pointcut, named sayMethodCall, that picks out any call to the TestClass.sayHello method. Moreover, it picks out any public TestClass method with zero arguments and a name that starts with “say” (for example, TestClass.sayBye).

Pointcuts are used in the definition of advice. An advice in AspectJ is used to define additional code to be executed before, after, or around join points. In our example, Lines 4–6 and 7–9 define two advices that will be executed before and after the first pointcut. Finally, Lines 10–15 implement an advice associated with the second pointcut and are used to set a precondition before the execution of the TestClass.sayAnyThing method.

Whereas pointcuts and advice let you affect the dynamic execution of a program, introduction allows aspects to modify the static structure of a program. By using introduction, aspects can add new methods and variables to a class, declare that a class implements an interface, or convert checked to unchecked exceptions. Introduction and a more practical application of AOP will be the subject of a future article.

AspectJ Compiler

Initially, you have to download the most recent version of AspectJ, available for free at its official site and install it. Compiling and running our example is very easy. Just write:

ajc MyAspect.aj TestClass.java
java TestClass

You should note that the source code at TestClass.java didn’t change. To return to the original functionality of your program, just use your Java compiler to re-compile it.

Related Links

About the Author

Yasser EL-Manzalawy has been a Java programmer and instructor since 1998. He is currently an assistant lecturer at the Systems & Computers Engineering Department, AZHAR University, Cairo. His Ph.D. research project aims to extend the Java language for agent-based systems.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories