You are on page 1of 28

Aspect Oriented Programming1

ACKNOWLEDGEMENT

First and foremost I thank God almighty for giving me strength, blessings and determination for the completion of my seminar named ASPECT ORIENTED PROGRAMMING. My endeavor stands incomplete without expressing gratitude to a few people who contributed much for making my seminar a success. It gives me immense pleasure to thank the Principal Prof. Bhadran V., College of Engineering Attingal for all his support and encouragement. I also express my heartfelt gratitude to Mrs.Suma L.S., the Head of Department of Computer Science for her immense inspiration and encouragement. I also extend my gratitude and thanks to Mrs.Sheeja Y.S, our staff advisor for her advice and support rendered to us. I also extend our sincere gratitude to Mrs.Shimja and Miss.Anushwara for the help and support. I do express our sincere thanks to my beloved family members and friends for all their encouragement, support and love.

KANZ

Department of Computer Science & Engg., CEA

Aspect Oriented Programming2

ABSTRACT
In commonly employed code, there are elements that are orthogonal to the primary functionality of the code. These elements, though extraneous to the primary purpose of the code, are vital to its proper execution. Furthermore, they tend to be scattered throughout the system so that they contribute to the complexity of the code. These elements are called aspects. Examples of aspects include processing to support security, fault-tolerance and synchronization. Aspectoriented programming (AOP) isolates aspects into separate modules so that the resulting client-code is more purpose-specific, more reusable, and less complex. AOP introduced to solve crosscutting problems of OOP. AOP is to OOP what OOP was to procedural languages (i.e. C++ to C). OOP does not allow strong implementation reuse. That is each class must either inherit one base class or use delegation (which breaks instance of tests).Another problem with OOP is certain software properties cannot be isolated in a single functional unit, instead they crosscut multiple components. Such crosscutting concerns result in tangled code that is hard to develop and maintain. In a general sense, the advance made by AOP has been its potential in complimenting OOP to develop an improved system. Certain aspects, like thread synchronization constraints and failure handling, are systemic in nature and present across components, which implies that they get tangled with the main functionality when developers employ conventional OOP approaches alone. AOP successfully captures these aspects, and isolates them as a separate entity. In the end, what results Department of Computer Science & Engg., CEA

Aspect Oriented Programming3 is a system that interweaves both OOP and AOP, and which is clearer and more focused on both the primary functionality and the aspects of its performance.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming4

INTRODUCTION
Object-oriented programming (OOP) has been presented as a technology that can fundamentally aid software engineering, because the underlying object model provides a better fit with real domain problems. However most software systems consist of several concerns that crosscut multiple modules. Object-oriented techniques for implementing such concerns result in systems that are invasive to implement, tough to understand, and difficult to evolve. This forces the implementation of those design decisions to be scattered throughout the code, resulting in tangled code that is excessively difficult to develop and maintain. The new aspect-oriented programming (AOP) methodology facilitates modularization of crosscutting concerns. Using AOP, you can create implementations that are easier to design, understand, and maintain. Further, AOP promises higher productivity, improved quality, and better ability to implement newer features.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming5

EVOLUTION OF THE SOFTWARE PROCESS


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. In the early days of computer science, developers wrote programs by means of direct machine-level coding. Unfortunately, programmers spent more time thinking about a particular machine's instruction set than the problem at hand. Slowly, we migrated to higher-level languages that allowed some abstraction of the underlying machine. Then came structured languages; we could now decompose our problems in terms of the procedures necessary to perform our tasks. However, as complexity grew, we needed better techniques. Object-oriented programming (OOP) let us view a system as a set of collaborating objects. Classes allow us to hide implementation details beneath interfaces. Polymorphism provided a common behavior and interface for related concepts, and allowed more specialized components to change a particular behavior without needing access to the implementation of base concepts.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming6 Programming methodologies and languages define the way we

communicate with machines. Each new methodology presents new ways to decompose problems: machine code, machine-independent code, procedures, classes, and so on. Each new methodology allowed a more natural mapping of system requirements to programming constructs. Evolution of these programming methodologies let us create systems with ever increasing complexity. The converse of this fact may be equally true: we allowed the existence of ever more complex systems because these techniques permitted us to deal with that complexity. Currently, OOP serves as the methodology of choice for most new software development projects. Indeed, OOP has shown its strength when it comes to modeling common behavior. However, as we will see shortly, and as you may have already experienced, OOP does not adequately address behaviors that span over many -- often unrelated -modules. In contrast, AOP methodology fills this void. AOP quite possibly represents the next big step in the evolution of programming methodologies.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming7

WHAT IS A CONCERN
A concern is a particular goal, concept, or area of interest. In technology terms, a typical software system comprises several core and system-level concerns. For example, a credit card processing system's core concern would process payments, while its system-level concerns would handle logging, transaction integrity, authentication, security, performance, and so on. Many such concerns -- known as crosscutting concerns -- tend to affect multiple implementation modules. Using current programming methodologies, crosscutting concerns span over multiple modules, resulting in systems that are harder to design, understand, implement, and evolve.

Aspect-oriented programming (AOP) separates concerns better than previous methodologies, thereby providing modularization of crosscutting concerns.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming8

CROSSCUTTING CONCERN PROBLEMS


Although crosscutting concerns span over many modules, current implementation using dimension techniques tend to implement these forcing requirements That single one-dimensional tends to be methodologies, the core

implementation mapping for the requirements along a single dimension. module-level implementation. The remaining requirements are tagged along this dominant dimension. In other words, the requirement space is an ndimensional space, whereas the implementation space is onedimensional. Such a mismatch results in an awkward requirements-toimplementation map.

Symptoms
A few symptoms can indicate a problematic implementation of crosscutting concerns using current methodologies.

Code

tangling:

Modules

in

software

system

may

simultaneously interact with several requirements. For example, oftentimes developers simultaneously think about business logic, performance, synchronization, logging, and security. Such a multitude of requirements results in the simultaneous presence of

Department of Computer Science & Engg., CEA

Aspect Oriented Programming9 elements from each concern's implementation, resulting in code tangling.

Code scattering: Since crosscutting concerns, by definition, spread over many modules, related implementations also spread over all those modules. For example, in a system using a database, performance concerns may affect all the modules accessing the database.

IMPLICATIONS

Combined, code tangling and code scattering affect software design and developments in many ways:

Poor

traceability:

Simultaneously

implementing

several

concerns obscures the correspondence between a concern and its implementation, resulting in a poor mapping between the two.

Lower productivity: Simultaneous implementation of multiple concerns shifts the developer's focus from the main concern to the peripheral concerns, leading to lower productivity.

Less code reuse: Since, under these circumstances, a module implements multiple concerns, other systems requiring similar functionality may not be able to readily use the module, further lowering productivity.

Poor code quality: Code tangling produces code with hidden problems. Moreover, by targeting too many concerns at once, one or more of those concerns will not receive enough attention.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming10 More difficult evolution: A limited view and constrained resources often produce a design that addresses only current concerns. Addressing future requirements often requires reworking the implementation. Since the implementation is not modularized, that means touching many modules. Modifying each subsystem for such changes can lead to inconsistencies. It also requires considerable testing effort to ensure that such implementation changes have not caused.

THE CURRENT RESPONSE


Since most systems include crosscutting concerns, it's no surprise that a few techniques Such have emerged include to mix-in modularize classes, their design implementation. techniques

patterns, and domain-specific solutions. With mix-in classes, for example, you can defer a concern's final implementation. The primary class contains a mix-in class instance and allows the system's other parts to set that instance. For example, in a credit card processing example, the class implementing business logic composes a logger mix-in. Another part of the system could set this logger to get the appropriate logging type. For example, the logger could be set to log using a file system or messaging middleware. Although the nature of logging is now deferred, the composer nevertheless contains code to invoke logging operations at all log points and controls the logging information. Department of Computer Science & Engg., CEA

Aspect Oriented Programming11 Behavioral design patterns, like Visitor and Template Method, let you defer implementation. However, just as in case with mix-ins, the control of the operation -- invoking visiting logic or invoking template methods -- stays with the main classes. Domain-specific solutions, such as frameworks and application servers, let developers address some crosscutting concerns in a modularized way. The Enterprise JavaBeans (EJB) architecture, for example, developers addresses focus on crosscutting the business concerns logic, such the as security, administration, performance, and container-managed persistence. Bean while deployment developers focus on deployment issues, such as bean-data mapping to a database. The bean developer remains, for the most part, oblivious to the storage issues. In this case, you implement the crosscutting concern of persistence using an XML-based mapping descriptor. The domain-specific solution offers a specialized mechanism for solving the specific problem. As a downside to domain-specific solutions, developers must learn new techniques for each such solution. Further, because these solutions are domain specific, the crosscutting concerns not directly addressed require an ad hoc response

The architect's dilemma


Good system architecture considers present and future

requirements to avoid a patchy-looking implementation. Therein lies a problem, however. Predicting the future is a difficult task. If you miss future crosscutting requirements, you'll need to change, or possibly reimplement, many parts of the system. On the other hand, focusing too much on low-probability requirements can lead to an overdesigned, confusing, bloated system. Thus a dilemma for system architects: How

Department of Computer Science & Engg., CEA

Aspect Oriented Programming12 much design is too much? Should I lean towards underdesign or overdesign? In summary, the architect seldom knows every possible concern the system may need to address. Even for requirements known beforehand, the specifics needed to create an implementation may not be fully available. Architecture thus faces the under/overdesign dilemma.

THE FUNDAMENTALS OF AOP


The scenario so far suggests that it can be helpful to modularize the implementation of crosscutting concerns. Researchers have studied various ways to accomplish that task under the more general topic of "separation of concerns." AOP represents one such method. AOP strives to cleanly separate concerns to overcome the problems discussed above.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming13 AOP, at its core, lets you implement individual concerns in a loosely coupled fashion, and combine these implementations to form the final system. Indeed, AOP creates systems using loosely coupled, modularized implementations of crosscutting concerns. OOP, in contrast, creates systems using loosely coupled, modularized implementations of common concerns. The modularization unit in AOP is called an aspect, just as a common concern's implementation in OOP is called a class.

View the system as a set of concerns


We can view a complex software system as a combined implementation of multiple concerns. A typical system may consist of several kinds of concerns, including business logic, performance, data persistence, logging and debugging, such authentication, as security, multithread safety, error checking, and so on. You'll also encounter development-process concerns, comprehensibility, maintainability, traceability, and evolution ease. Figure 1 illustrates a system as a set of concerns implemented by various modules.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming14

Figure 1. Implementation modules as a set of concerns

Figure 2 presents a set of requirements as a light beam passing through a prism. We pass a requirements light beam through a concern-identifier prism, which separates each concern. The same view also extends towards development-process concerns.

Figure 2. Concern decomposition: The prism Department of Computer Science & Engg., CEA

Aspect Oriented Programming15

analogy

Crosscutting concerns in a system

A developer creates a system as a response to multiple requirements. We can broadly classify these requirements as core module-level system-level requirements requirements and tend system-level to be requirements. orthogonal Many (mutually

independent) to each other and to the module-level requirements. System-level requirements also tend to crosscut many core modules. For example, a typical enterprise application comprises crosscutting concerns such as authentication, logging, resource pooling, administration, performance, and storage management. Each crosscuts several subsystems. For example, a storage-management concern affects every stateful business object.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming16

DEVELOPMENT STEPS IN AOP


1. Aspectual decomposition: Decompose the requirements to identify crosscutting and common concerns. Separate modulelevel concerns from crosscutting system-level concerns. 2. Concern implementation: Implement each concern separately. For the credit card processing example, you'd implement the core credit card processing unit, logging unit, and authentication unit. 3. Aspectual recomposition: In this step, an aspect integrator specifies recomposition rules by creating modularization units -aspects. The recomposition process, also known as weaving or integrating, uses this information to compose the final system. For the credit card processing example, you'd specify, in a language provided by the AOP implementation, that each operation's start and completion be logged. You would also specify that each operation must clear authentication before it proceeds with the business logic.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming17 AOP development stages AOP differs most from OOP in the way it addresses crosscutting concerns. With AOP, each concern's implementation remains unaware that other concerns are "aspecting" it. For example, the credit card processing module doesn't know that the other concerns are logging or authenticating its operations. That represents a powerful paradigm shift from OOP.

Weaving example
The weaver, a processor, assembles an individual concern in a process known as weaving. The weaver, in other words, interlaces different execution-logic fragments according to some criteria supplied to it. To illustrate code weaving, let's consider a our credit card processing system example. For brevity, consider only two operations: credit and debit. Also assume that a suitable logger is available. Consider the following credit card processing module: public class CreditCardProcessor { public void debit(CreditCard card, Currency amount) throws InvalidCardException, NotEnoughAmountException, CardExpiredException { // Debiting logic } public void credit(CreditCard card, Currency amount) throws InvalidCardException { // Crediting logic } } Department of Computer Science & Engg., CEA

Aspect Oriented Programming18 Also, consider the following logging interface: public interface Logger { public void log(String message); } The desired composition requires the following weaving rules, expressed here in natural language (a programming language version of these weaving rules is provided later ): 1. Log each public operation's beginning 2. Log each public operation's completion 3. Log any exception thrown by each public operation The weaver would then use these weaving rules and concern implementations to produce the equivalent of the following composed code: public class CreditCardProcessorWithLogging { Logger _logger; public void debit(CreditCard card, Money amount) throws InvalidCardException, NotEnoughAmountException, CardExpiredException { _logger.log("Starting CreditCardProcessor.credit(CreditCard, Money) " + "Card: " + card + " Amount: " + amount); // Debiting logic _logger.log("Completing CreditCardProcessor.credit(CreditCard, Money) " + "Card: " + card + " Amount: " + amount); }

Department of Computer Science & Engg., CEA

Aspect Oriented Programming19

public void credit(CreditCard card, Money amount) throws InvalidCardException { System.out.println("Debiting"); _logger.log("Starting CreditCardProcessor.debit(CreditCard, Money) " + "Card: " + card + " Amount: " + amount); // Crediting logic _logger.log("Completing CreditCardProcessor.credit(CreditCard, Money) " + "Card: " + card + " Amount: " + amount); } }

Department of Computer Science & Engg., CEA

Aspect Oriented Programming20

ANATOMY OF AOP LANGUAGES

Just like any other programming methodology implementation, an AOP implementation consists of two parts: a language specification and an implementation. The language specification describes language constructs and syntax. The language implementation verifies the code's correctness according to the language specification and converts it into a form that the target machine can execute.

The AOP language specification

At a higher level, an AOP language specifies two components:

Implementation

of

concerns:

Mapping

an

individual

requirement into code so that a compiler can translate it into executable code. Since implementation of concerns takes the form of specifying procedures, you can to use traditional languages like C, C++, or Java with AOP.

Weaving rules specification: How to compose independently implemented concerns to form the final system. For this purpose, an implementation needs to use or create a language for specifying rules for composing different implementation pieces to form the final system. The language for specifying weaving rules

Department of Computer Science & Engg., CEA

Aspect Oriented Programming21 could be an extension of the implementation language, or something entirely different.

AOP language implementation

AOP language compilers perform two logical steps: 1. Combine the individual concerns 2. Convert the resulting information into executable code An AOP implementation can implement the weaver in various ways, including source-to-source translation. Here, you preprocess source code for individual aspects to produce weaved source code. The AOP compiler then feeds this converted code to the base language compiler to produce final executable code. For instance, using this approach, a Javabased AOP implementation would convert individual aspects first into Java source code, then let the Java compiler convert it into byte code. The same approach can perform weaving at the byte code level; after all, byte code is still a kind of source code. Moreover, the underlying execution system -- a VM implementation, say -- could be aspect aware. Using this approach for Java-based AOP implementation, for example, the VM would load weaving rules first, then apply those rules to subsequently loaded classes. In other words, it could perform just-intime aspect weaving.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming22

ASPECTJ: AN AOP IMPLEMENTATION FOR JAVA


AspectJ, a freely available AOP implementation for Java from Xerox PARC, is a general-purpose aspect-oriented Java extension. AspectJ uses Java as the language for implementing individual concerns, and it specifies extensions to Java for weaving rules. These rules are specified in terms of pointcuts, join points, advice, and aspects. Join points define specific points in a program's execution, a pointcut is the language construct that specifies join points, advice defines pieces of an aspect implementation to be executed at pointcuts, and an aspect combines these primitives. In addition, AspectJ also allows the "aspecting" of other aspects and classes in several ways. Indeed, we can introduce new data members and new methods, as well as declare a class to implement additional base classes and interfaces. AspectJ's weaver -- an aspect compiler -- combines different aspects together. Because the final system created by the AspectJ compiler is pure Java byte code, it can run on any conforming JVM. AspectJ also features tools such as a debugger and selected IDE integration.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming23 Below an AspectJ implementation of the logging aspect for the weaver described in natural language previously public aspect LogCreditCardProcessorOperations { Logger logger = new StdoutLogger(); pointcut publicOperation(): execution(public * CreditCardProcessor.*(..)); pointcut publicOperationCardAmountArgs(CreditCard card, Money amount): publicOperation() && args(card, amount); before(CreditCard card, Money amount): publicOperationCardAmountArgs(card, amount) { logOperation("Starting", thisjoin point.getSignature().toString(), card, amount); } after(CreditCard card, Money amount) returning: publicOperationCardAmountArgs(card, amount) { logOperation("Completing", thisjoin point.getSignature().toString(), card, amount); } after (CreditCard card, Money amount) throwing (Exception e): publicOperationCardAmountArgs(card, amount) { logOperation("Exception " + e, thisjoin point.getSignature().toString(), card, amount); } private void logOperation(String status, String operation, Department of Computer Science & Engg., CEA

Aspect Oriented Programming24 CreditCard card, Money amount) { logger.log(status + " " + operation + " Card: " + card + " Amount: " + amount); } }

AOP BENEFITS
AOP helps overcome the aforementioned problems caused by code tangling and code scattering. Here are other specific benefits AOP offers:

Modularized implementation of crosscutting concerns: AOP addresses each concern separately with minimal coupling, resulting in modularized implementations even in the presence of crosscutting concerns. Such an implementation produces a system with less duplicated code. Since each concern's implementation is separate, it also helps reduce code clutter. Further, modularized implementation also results in a system that is easier to understand and maintain.

Easier-to-evolve systems: Since the aspected modules can be unaware of crosscutting concerns, it's easy to add newer functionality by creating new aspects. Further, when you add new modules to a system, the existing aspects crosscut them, helping create a coherent evolution.

Late binding of design decisions: Recall the architect's under/overdesign dilemma. With AOP, an architect can delay

Department of Computer Science & Engg., CEA

Aspect Oriented Programming25 making design decisions for future requirements, since she can implement those as separate aspects.

More code reuse: Because AOP implements each aspect as a separate module, each individual module is more loosely coupled. For example, you can use a module interacting with a database in a separate logger aspect with a different logging requirement. In general, a loosely coupled implementation represents the key to higher code reuse. AOP enables more loosely coupled implementations than OOP.

AOP statistics
1. On reengineering a particular image processing program the following results were obtained

2.

In the original FreeBSD v3.3 code, the implementation of

prefetching is both scattered and tangled. The code is spread out over approximately 260 lines in 10 clusters in 5 core functions from two subsystems. On using AOP the resulting code was spread over two pages of 50 lines each.

Department of Computer Science & Engg., CEA

Aspect Oriented Programming26

AOP APPLICATIONS
a-kernel is an effort to apply AOP techniques to operating system kernel code. FACET is a framework for a customizable real-time event channel that uses aspects. Lasagne is an aspect-oriented architecture for contextsensitive and run-time weaving of aspects--prototypes have been developed in Java and Correlate. QuO is a middleware framework and toolkit which includes aspect-oriented languages for developing quality of service enabled, adaptive distributed object applications. SoC+MAS is a research project whose main focus is the application of advanced separation of concerns techniques to handle the complexity of designing and implementing multi-agent OO software. SADES is a customizable and extensible object database
Department of Computer Science & Engg., CEA

Aspect Oriented Programming27

evolution system implemented using AOP techniques

REFERENCES

Aspect oriented software development sites http://www. parc.xerox.com http://www.aosd.net http://www.aspectj.org http://www.javaworld.com IBM research site http://www.research.ibm.com Microsoft MSDN site http://msdn.microsoft.com

Department of Computer Science & Engg., CEA

Aspect Oriented Programming28

Department of Computer Science & Engg., CEA