Paradigm Shift in Programming: from OOP to AOP

When Object-Oriented (OO) programming entered the mainstream of software development, it had a dramatic effect on how software was developed. Developers could visualize systems as groups of entities and the interaction between those entities, which allowed them to tackle larger, more complicated systems and develop them in less time than ever before. The only problem with OO programming is that it is essentially static, and a change in requirements can have a profound impact on development timelines. Aspect-Oriented Programming (AOP) complements OO programming by allowing the developer to dynamically modify the static OO model to create a system that can grow to meet new requirements. Just as objects in the real world can change their states during their lifecycles, an application can adopt new characteristics as it develops. AOP allows us to dynamically modify our static model to include the code required to fulfill the secondary requirements without having to modify the original static model (in fact, we don't even need to have the original code). This article covers AOP in Java and .Net environment so that the developers can utilize it according to their requirements. In this article,the basic AOP concepts as well as how to apply AOP to applications are explored.

Introduction

Aspect-oriented programming (AOP) is a new paradigm and technology that allows solving complex problems in software that cannot be simply solved using object-oriented programming. The concepts of AOP have first been defined and explored by Gregor Kiczales' team at Xerox Parc in the late 1990s. Since then, many AOP frameworks have emerged in the Java landscape and many experts in the software industry talks about AOP as something that will revolutionize the 
way we design and write software.

AOP Terminology

Before we delve too deeply into AOP, it’s important to introduce some standard terminology to help and understand the concepts:

1. Cross-cutting concerns: Even though most classes in an OO 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. Even though the primary functionality of each class is very different, the code needed to perform the secondary functionality is often identical.

2. Advice: This is the additional code that you want to apply to your existing model. 

3. Point-cut: This is the term given to the point of execution in the application at which cross-cutting concern needs to be applied. 

4. Aspect: The combination of the point-cut and the advice is termed an aspect. 

The key to AOP is modularization. Each program contains aspects that are not specific for that application domain. For instance, the way error handling, logging, or tracing is handled is often identical over multiple domains. AOP tells us that these aspects should be contained in different modules, and indeed aspect is the name used for such a module. The modules that contain the application-specific code and the non-specific aspect module, or modules, are then woven together to create the application (Figure-1).



(Figure-1: Aspect Weaving- Application code and aspects are woven together to get the finished product in AOP)

The application-specific code and the aspects can be developed independently. The application-specific code need not know what aspects will be added, leaving the developer to concentrate on implementing the required functionality—the business logic. Likewise, the author of the aspects does not need to know the application-specific code. The only knowledge necessary for writing aspects would be the join points. Join points are identifiable events in the execution of a program. The developer of a logging aspect, for instance, would have to know about method calls and the aspect would specify that whenever a method is called, a message would be added to the log. 
Join points can be identified by the aspect using pointcut expressions. Pointcut expressions specify join points, much as classes specify object instances.

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 example 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-2 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.



Types of AOP Compilers

AOP compilers comes in different flavors and the type of weaving decides what type of compiler is it. There are four types of compilers or to be specific weaving types in AOP :

· Compile time weaving :- This type of weaving happens at the compiler level and is not supported currently in .NET. In compile time Core concern code and the cross cut code is weaved before been compiled to MSIL code. So before the JIT compilation takes place using .NET compilers Aspect code is compiled and fed to the main the compiler. There are many third party compilers which are available which extend the .NET compiler module and implement this feature. 

· Link time Weaving :- This type of compilers compile core and cross cut code after the MSIL is generated. Again this has to be done at linker level. So at this moment not supported , we will either have to use third party or wait for Microsoft's AOP compiler. 

· Run time weaving :- This type of weaving is done by using the .NET runtime. In short your code detects the core , cross cut etc and executes them at run time. This is supported at this moment in .NET and we will see how we can implement Run time weaving. 

Designing an Aspect Framework

Aspect framework requires the following features:
· A runtime for stringing aspects together between a client and an object.
· User-defined aspects implemented as COM components.
· Metadata descriptions of which aspects were associated with each COM component, just like the COM+ Catalog.
· A method that clients can use to activate components with the aspects in place.


The AOP framework performs two distinct steps, component activation and method invocation. In component activation, the AOP framework builds the stack of aspect implementation objects and returns a reference to an interceptor instead of a reference to the actual object. In method invocation, when the caller makes method calls on the interceptor, the interceptor delegates the calls to all the registered aspects for preprocessing of [in] and [in,out] arguments on the call stack, and delivers the actual call to the object. Then it delivers the call to the aspects for post-processing by passing the return value of the call that the component returned, the [in,out] and [out] arguments on the call stack.



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

Whereas OOP doctrine is to group functionality into objects and create relationships between those objects, AOP says to think of functionality (here called aspects or concerns) as being independent from any class. AOP primarily deals with what are called crosscutting concerns, which are aspects of functionality that are needed but are unrelated to the actual behavior of the class in which they're needed.
Aspects can be plugged into code at join points—places such as method calls, field access, and exception handling. You must give instructions (advice in AOP-speak) for what to do at these join points. Exactly how you provide advice differs widely depending on which AOP implementation you're using, but often it's via something like an XML configuration file or metadata within code, generally using something like regular expressions to identify join points.

AOP also gives developers access to compile-time behavior much like multiple inheritance, called introductions. With introductions, you can force a certain class to implement a separate interface, without touching the code of the class itself.

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 
· AspectWerkz 
· HyperJ 
· JAC 
· JMangler 
· MixJuice 
· PROSE 
· ArchJava 

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

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, consider the following simple example.

Code-1

Join points, Pointcut, Advice, and Introduction
TestClass.java

--------------------------------------------------
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");
}
--------------------------------------------------

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 Code is the AspectJ implementation.

Code-2

MyAspect.aj
-----------------------------------------------------------------------------------------------
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: }


Initially, you have to download (http://www.eclipse.org/aspectj/) 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.

Code-3

Code of AOPServlet
-----------------------------------------------------
package example;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AOPServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Person person = new Person();
if (request.getParameter("name") != null) {
person.setName(
request.getParameter("name"));
}
if (request.getParameter("email") != null) {
person.setEmail(
request.getParameter("email"));
}
request.setAttribute("person", person);
RequestDispatcher rd =
request.getRequestDispatcher("/view.jsp");
rd.forward(request, response);
}
}

In the above example, we can notice that the servlet code is very minimal; it only contains enough code to create an object to bind the request parameters to, and then it passes the object along in the request. There is no persistence code, no additional imports; it simply does what it meant to do.

The next section defines aspects. This is where we map our advice to a point-cut to create an aspect. 

Code-4

------------------------------------
<aspect name="servlet">
<pointcut-def name="all" type="method"
pattern="* example.*Servlet.doGet(..)"/>
<bind-advice pointcut="all">
<advice-ref name="persist"/>
</bind-advice>
</aspect>
------------------------------------

AOP in Microsoft.NET

This is the next part of articles to describe Aspect.NET – an aspect-oriented programming (AOP) framework for Microsoft.NET based on a number of new ideas. This section presents the current status of Aspect.NET – its design principles, its working version – and gives some practical examples.

In this section we’ll demonstrate how Aspect.NET helps to develop well-structured and clearly implemented applications, using the power of AOP as part of Visual Studio.NET .

Aspect.NET Design Approach

Aspect.NET is a language-agnostic visual environment for developing aspect-oriented applications for Microsoft.NET that was implemented as an add-in to Microsoft Visual Studio.NET . Using Aspect.NET, the user can define and weave aspects and assess the results of the weaving in his or her projects.

An aspect definition consists of: 
· header (with optional formal parameters) 
· data (optional) 
· modules (classes, methods, functions, etc.) 
· actions (method calls or just statements) 
· weaving rules for each action in Aspect.NET metalanguage

The Aspect.NET tool has the following three main components:
· Aspect editor: Allows you to add new aspects, browse, and select (or unselect) the potential joinpoints found in the source .
· Weaver: Statically weaves the selected aspects to the selected joinpoints of the target assembly. The process of joining the aspect with the target assembly consists of the some phases. 
· Converters: Convert from Aspect.NET AOP metalanguage to attribute annotations (currently implemented for C#.NET and VB.NET). 

Code-5

An example of a profiling aspect. . For weaving the aspect into different kinds of join points and according to different kinds of rules, the %action declaration should be updated only.
------------------------------------------------------
%aspect AspectProfiler
public class AspectProfiler
{

%modules
static private DateTime StartTime;
static private DateTime EndTime;

public static void StartTimeUpdate()
{
StartTime = DateTime.Now;
}

public static void EndTimeUpdate()
{
EndTime = DateTime.Now;
}

%rules 
%action %before %call *OrderSystem.StartOrderProcessing
public static void ActionBeforeCall(string methname)
{
AspectProfiler.StartTimeUpdate(); 
}

%action %after %call *OrderSystem.StartOrderProcessing
public static void ActionAfterCall(string methname)
{
AspectProfiler.EndTimeUpdate();
if (StartTime.Ticks != 0)

TimeSpan tsp = EndTime.Subtract(StartTime);
System.Console.WriteLine(“AspectProfiler: Executing time of 
{0}: {1} milliseconds”, methname, tsp.Ticks/10000);

}
}

}//AspectProfiler
-----------------------------------

Code-6

The Client class of the ordering system

----------------------------------------------------------
//Client.cs
class Client 
{
public string Name;
public double Account;

public Client(string _Name, double _Account) 

Name = _Name; Account = _Account; 
}

public void CreditOperation(double Amount)
{
Account -= Amount;
ProcessOperation(); // Perform time consuming further processing
}

public void DebitOperation(double Amount)
{
Account += Amount;
ProcessOperation(); // Perform time consuming further processing 
}

public void ProcessOperation()
{
Thread.Sleep(2000); // Emulation of processing
}

}//Client
------------------------------------------------

Code-7

The OrderSystem class of the ordering system
--------------------------------------------------------
//Program.cs
class OrderSystem
{
public Hashtable ActiveClients;

public OrderSystem(Hashtable _Clients) {ActiveClients = _Clients;}

static void Main(string[] args)
{
Hashtable ActiveClientsTable = new Hashtable();
ActiveClientsTable.Add(“John”, new Client(“John”, 100));
ActiveClientsTable.Add(“Bob”, new Client(“Bob”, 250));
OrderSystem os = new OrderSystem(ActiveClientsTable);
os.StartOrderProcessing();
//Printing somehow ActiveClients table on the console...
}

public void StartOrderProcessing()
{
Client John = (Client)ActiveClients[“John”];
Client Bob = (Client)ActiveClients[“Bob”];
John.CreditOperation(250);
Bob.DebitOperation(250); 
}
}// OrderSystem
------------------------------------------

Code-8

The AsyncCallAspect
-------------------------------------------------------------------
%aspect AsyncCallAspect
public class AsyncCallAspect
{
%modules 
static private ArrayList ThreadsPool = null;

%rules 
%action %instead %call *Client.ProcessOperation
static public void WrapMethodWithAsyncCall
(string FullMethodName, Object target)

if (ThreadsPool == null)
ThreadsPool = new ArrayList();

string ShortMethodName = 
FullMethodName.Substring(FullMethodName.LastIndexOf(“.”)+1);

MethodInfo mi = target.GetType().GetMethod(ShortMethodName);
ThreadStart ts = 
(ThreadStart)ThreadStart.CreateDelegate(typeof(ThreadStart), 
target, mi);
Thread thread = new Thread(ts);
ThreadsPool.Add(thread);
thread.Start();
}

%action %after %call *OrderSystem.StartOrderProcessing
static public void TotalJoining()
{
if (ThreadsPool != null)
{
foreach (Thread t in ThreadsPool)
t.Join();
}
}
}// AsyncCallAspect
----------------------------------------------

Code-9

CreditAbilityAspect and TransactionalAspect
---------------------------------------------
%aspect CreditAbilityAspect
public class CreditAbilityAspect
{
%rules 
%action %after %call *Client.CreditOperation
public static void CreditOverflowAssertion
(string FullMethodName, Object target)
{
Type TargetType = target.GetType();
double ClientAccount = 
(double) TargetType.GetField(“Account”).GetValue(target);
if(ClientAccount < 0)
throw new Exception(“Account exceeded!”);
}
}// CreditAbilityAspect

%aspect TransactionalAspect
public class TransactionalAspect
{
%modules 
static protected void BackupSystemState(Object target)
{
//Store somehow this.ActiveClients table
}

static protected void RecoverSystemState(Object target)
{
//Copy previously stored ActiveClients to this.ActiveClients
}

%rules 
%action %instead %call *OrderSystem.StartOrderProcessing
public static void AroundTransaction(string FullMethodName, 
Object target)
{
string ShortMethName = 
FullMethodName.Substring(FullMethodName.LastIndexOf(“.”)+1);
Type TargetType = target.GetType();
// ... Saving state of the system for further recovering
BackupSystemState(target);
try
{
TargetType.GetMethod(ShortMethName).Invoke(target, null);
//...Commit transaction
}
catch (Exception e) //...Rolling back transactions

{
Console.WriteLine(“Rolling back transactions...”);
RecoverSystemState(target);
}
}
}// TransactionalAspect

--------------------------------------------------------------
Please visit www.microsoft.com for more detail about AOP in .Net framework.

Conclusion

Aspect-oriented programming is an emerging technology that can help us to solve concrete real-world problems and build new interesting architectures. In this article you have learned basic concepts of aspect-oriented programming and how it can be used to implement an application.

Due to the development of the Microsoft.NET platform, the developers get more and more opportunities that were unavailable before. AOP lets a software developer concentrate mostly on the business logic of his or her project, by implementing auxiliary features as special kinds of reusable modules – aspects. Interaction of aspects to the core code of the project is defined in a high-level metalanguage that does not depend on the project implementation language. These loosely coupled software components can be developed independently. Keeping in mind the tendency toward distributed software system development, using AOP can greatly decrease the cost of software products. Whereas for the Java platform there are a lot of powerful AOP tools, we expect that, due to further development of Microsoft Phoenix and Visual Studio.NET, more and more AOP systems will be also developed for .NET and integrated to the oncoming versions 
of Visual Studio.

References and Web Links

· Aspect-Oriented Software Development with Use Cases, Ivar Jacobson and Pan-Wei NG, Addison Wesley.
· Mastering AspectJ, Joseph D. Gradecki and Nicholas Lesiecki, John Wiley. 
· http://www.eclipse.org/aspectj/
· AOP tools comparison: www.ibm.com/developerworks/java/library/j-aopwork1/
· www.microsoft.com
· www.sun.com
---------------------------- end----------------


About the Authors

1. Sunil Kr.Pandey
Asst. Professor
Department of Computer Science,
School of Management Sciences(SMS),
Varanasi(UP)
India.
E-mail:sunilmca5@rediffmail.com
2. R.B.Mishra
Reader
Department of Computer Engineering 
Institute of Technology(IT),
Banaras Hindu University(BHU),
Varanasi(UP)
India.



Added on December 7, 2007 Comment

Comments

Post a comment

Your name:

Comment: