CSC/ECE 517 Fall 2009/wiki2 9 SN

From Expertiza_Wiki
Jump to navigation Jump to search

Aspect-Oriented Programming

Traditional software development has focused on developing systems into units of primary functionality, while recognizing that there are other issues of concern that do not fit well into the primary decomposition. This process leaves it to the programmers to code modules corresponding to the primary functionality and to make sure that all other issues of concern are addressed in the code wherever appropriate. Programmers need to keep in mind all the things that need to be done, how to deal with each issue, the problems associated with the possible interactions, and the execution of the right behavior at the right time. When all these things are taken into account, this often results in serious issues being raised during the development and maintenance of a large software system.

Aspect-Oriented programming focuses on the identification, specification, and representation of crosscutting concerns and their modularization into separate functional units as well as their automated composition into a working system.

So What exactly is AOP?

Introduction

Software design processes and programming languages exist in a mutually supporting relationship. Design processes break a system down into smaller and smaller units. Programming languages provide mechanisms that allow the programmer to define abstractions of system sub-units, and then compose those abstractions in different ways to produce the overall system. A design process and a programming language work well together when the programming language provides abstraction and composition mechanisms that cleanly support the kinds of units the design process breaks the system into. From this perspective, many existing programming languages, including object-oriented languages, procedural languages, and functional languages, can be seen as having a common root in that their key abstraction and composition mechanisms are all rooted in some form of generalized procedure.

Aspect-oriented programming is a programming process that entails breaking down a program into distinct parts or what are called 'concerns.' This process is called separation of concerns. Often times these concerns overlap and this is called crosscutting concerns. All AOP implementations have some crosscutting expressions that encapsulate each concern in one place. The difference between implementations lies in the power, safety, and usability of the constructs provided.

Terminology

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. Even though the primary functionality of each class is very different, 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.

Point-cut

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

Aspect

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

Overview

AOP encapsulates crosscutting concerns into a single program module called an aspect, which can add behavior to a program and verify or change its static structure. The aspect specifies join points in the running program using point-cuts, and permits advice code to run around the join point, to join the advice behavior to the program semantics. The aspect can also declare members and super-types of other classes if the declarations are type-safe, binary-compatible and respect access rules. The combination of advice and inter-type declarations enables one to implement the correct associations and behaviors for many objects in one aspect.

Mechanisms for defining and composing abstractions are essential elements of programming languages. The design style supported by the abstraction mechanisms of most current languages is one of breaking a system down into parametrized components that can be called upon to perform a function. But many systems have properties that don't necessarily align with the system's functional components, such as failure handling, persistence, communication, replication, coordination, memory management, or real-time constraints, and tend to cut across groups of functional components.

While they can be thought about and analyzed relatively separately from the basic functionality, programming them using current component-oriented languages tends to result in these aspects being spread throughout the code. The source code becomes a tangled mess of instructions for different purposes.

This phenomenon is at the heart of much needless complexity in existing software systems. A number of researchers have begun working on approaches to this problem that allow programmers to express each of a system's aspects of concern in a separate and natural form, and then automatically combine those separate descriptions into a final executable form. These approaches have been called aspect-oriented programming.

OOP and AOP at a Glance

Object-oriented programming 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.

AOP is a way to modularize code that is typically repeated and sandwiched all over in an object-oriented system. AOP is used for separating crosscutting concerns into single units called aspects. With AOP, we start by implementing our project using our OO language , 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 re-usability and maintainability of the code.

AspectJ

AspectJ is a seamless aspect-oriented extension to the Java programming language that enables clean modularization of these 'crosscutting concerns'. Some aspects of system implementation, such as logging, error handling, standards enforcement and feature variations are notoriously difficult to implement in a modular way. The result is that code is tangled across a system and leads to quality, productivity and maintenance problems.

AspectJ is a simple, practical, and compatible aspect-oriented extension to Java.

  • Upward compatibility — all legal Java programs must be legal AspectJ programs.
  • Platform compatibility — all legal AspectJ programs must run on standard Java virtual machines.
  • Tool compatibility — it must be possible to extend existing tools to support AspectJ in a natural way; this includes IDEs, documentation tools, and design tools.
  • Programmer compatibility — Programming with AspectJ must feel like a natural extension of programming with Java.

Example

The best way to understand AspectJ is through example. Lets say we have a simple Hello World program.

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

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.


 public aspect MyAspect 
 {
  public pointcut sayMethodCall (): call (public void TestClass.say*() );
  public pointcut sayMethodCallArg (String str): call
                    (public void TestClass.sayAnyThing (String)) && args(str);
  before(): sayMethodCall() 
  {
    System.out.println("\n TestClass." +
      thisJoinPointStaticPart.getSignature().getName() + "start..." );
  }
  after(): sayMethodCall() 
  {
    System.out.println("\n TestClass." +
      thisJoinPointStaticPart.getSignature().getName() + " end...");
  }
  before(String str): sayMethodCallArg(str) 
  {
    if (str .length() < 3) 
    {
      System.out.println ("Error: I can't say words less than 3 characters");
      return;
    }
  }
 }

AspectR

AspectR is the AOP Language for Ruby. It was modeled after and resembles a lot like AspectJ.

There are some differences which AspectR does not have that AspectJ does:

  • Join points: method/constructor called, method/constructor executes (?), exception handler executes
  • Most of the point-cut designator primitives
  • Composition of point-cut designators
  • 'around' advices
  • precedence/specificity among advices/aspects
  • reflection by sending join-point object to advices with context of join point etc
  • control-flow based crosscutting

AspectR lets a module wrap any number of methods in other classes with the advice methods of the module.

Example

 require 'aspectr'
 include AspectR
 class MyAspect < Aspect
       def someAdviceMethod(method, object, exitstatus, *args)
            ...
       end
       ... some other advice methods ...
 end
 ma = MyAspect.new
 ma.wrap(someClassorObject, :preAdvice, :postAdvice, ... methods to wrap...) or
 ma.wrap(someClassorObject, :preAdvice, :postAdvice, /patternToWrap/) or
 AspectR.wrap_classes(ma, :preAdvice, :postAdvice,
 [Class1, Class2], ...methods to wrap...)

Advice methods are passed a variable number of parameters.

The first parameter is the name of the method currently being wrapped.

The second parameter is the object receiving the method call.

The third parameter is the exit/return status:

  • Array with return value(s) if the method exited normally
  • True if the method exited with an exception
  • Nil if the method hasn't yet exited


Conclusion

Aspect-Oriented Programming an emerging software development technology that seeks new modularization of software systems. The technology allows for a more robust and sound software system. Not only has the benefits and clarity of Object-Oriented programming, but AOP provides an easier way to correlate different aspects of a software system into one single solution. Often too many programs and software systems are incomplete or not ideal because one aspect is treated greater than the other. AOP attempts to balance the aspects in such a way that the software system has a much more functional and reusable architecture.

Links

1. AOP Developer

2. AOP and Adaptive Programming

3. Java AOP

4. Aspect Programming

5. AspectJ

6. AspectR

7. AOP in Ruby