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. CEA . and which is clearer and more focused on both the primary functionality and the aspects of its performance.. Department of Computer Science & Engg.

and maintain. This forces the implementation of those design decisions to be scattered throughout the code. Further. and better ability to implement newer features.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. resulting in “tangled” code that is excessively difficult to develop and maintain. Object-oriented techniques for implementing such concerns result in systems that are invasive to implement. The new aspect-oriented programming (AOP) methodology facilitates modularization of crosscutting concerns. understand.. tough to understand. CEA . Department of Computer Science & Engg. and difficult to evolve. improved quality. Using AOP. you can create implementations that are easier to design. AOP promises higher productivity.

we could now decompose our problems in terms of the procedures necessary to perform our tasks. 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. programmers spent more time thinking about a particular machine's instruction set than the problem at hand. and then compose those abstractions in different ways to produce the overall system. Programming languages provide mechanisms that allow the programmer to define abstractions of system sub-units. we migrated to higher-level languages that allowed some abstraction of the underlying machine. developers wrote programs by means of direct machine-level coding. Design processes break a system down into smaller and smaller units. Classes allow us to hide implementation details beneath interfaces. Slowly. CEA . In the early days of computer science. and allowed more specialized components to change a particular behavior without needing access to the implementation of base concepts. as complexity grew. Polymorphism provided a common behavior and interface for related concepts. Then came structured languages.Aspect Oriented Programming5 EVOLUTION OF THE SOFTWARE PROCESS Software design processes and programming languages exist in a mutually supporting relationship.. Object-oriented programming (OOP) let us view a system as a set of collaborating objects. we needed better techniques. Unfortunately. However. Department of Computer Science & Engg.

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. CEA . OOP serves as the methodology of choice for most new software development projects. OOP has shown its strength when it comes to modeling common behavior. In contrast.. and as you may have already experienced.often unrelated -modules. Evolution of these programming methodologies let us create systems with ever increasing complexity. However.Aspect Oriented Programming6 Programming methodologies and languages define the way we communicate with machines. Currently. classes. Indeed. Department of Computer Science & Engg. and so on. machine-independent code. OOP does not adequately address behaviors that span over many -. Each new methodology presents new ways to decompose problems: machine code. AOP quite possibly represents the next big step in the evolution of programming methodologies. Each new methodology allowed a more natural mapping of system requirements to programming constructs. as we will see shortly. AOP methodology fills this void. procedures.

thereby providing modularization of crosscutting concerns. resulting in systems that are harder to design. performance.known as crosscutting concerns -.Aspect Oriented Programming7 WHAT IS A CONCERN A concern is a particular goal. and evolve. and so on. concept. a credit card processing system's core concern would process payments. In technology terms. or area of interest. transaction integrity. implement. a typical software system comprises several core and system-level concerns. CEA . Many such concerns -. authentication.tend to affect multiple implementation modules. security. Aspect-oriented programming (AOP) separates concerns better than previous methodologies.. Department of Computer Science & Engg. understand. Using current programming methodologies. For example. while its system-level concerns would handle logging. crosscutting concerns span over multiple modules.

. performance. • Code tangling: Modules in a software system may simultaneously interact with several requirements. For example. Such a multitude of requirements results in the simultaneous presence of Department of Computer Science & Engg. and security. logging. oftentimes developers simultaneously think about business logic. CEA . synchronization. The remaining requirements are tagged along this dominant dimension. the requirement space is an ndimensional space. the core implementation mapping for the requirements along a single dimension. Symptoms A few symptoms can indicate a problematic implementation of crosscutting concerns using current methodologies. current implementation using dimension techniques tend to implement these forcing requirements That single one-dimensional tends to be methodologies. Such a mismatch results in an awkward requirements-toimplementation map. module-level implementation. In other words.Aspect Oriented Programming8 CROSSCUTTING CONCERN PROBLEMS Although crosscutting concerns span over many modules. whereas the implementation space is onedimensional.

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. IMPLICATIONS Combined. Moreover. • Poor code quality: Code tangling produces code with hidden problems. • Code scattering: Since crosscutting concerns. further lowering productivity. • Lower productivity: Simultaneous implementation of multiple concerns shifts the developer's focus from the main concern to the peripheral concerns. Department of Computer Science & Engg. under these circumstances. other systems requiring similar functionality may not be able to readily use the module. in a system using a database. by definition. one or more of those concerns will not receive enough attention. by targeting too many concerns at once.Aspect Oriented Programming9 elements from each concern's implementation. For example. performance concerns may affect all the modules accessing the database. a module implements multiple concerns. spread over many modules. resulting in code tangling. CEA . related implementations also spread over all those modules. • Less code reuse: Since. leading to lower productivity.

Although the nature of logging is now deferred.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. their design implementation. that means touching many modules. For example. the composer nevertheless contains code to invoke logging operations at all log points and controls the logging information. the logger could be set to log using a file system or messaging middleware. the class implementing business logic composes a logger mix-in. Department of Computer Science & Engg. techniques patterns. • THE CURRENT RESPONSE Since most systems include crosscutting concerns. With mix-in classes. The primary class contains a mix-in class instance and allows the system's other parts to set that instance. Modifying each subsystem for such changes can lead to inconsistencies. in a credit card processing example. CEA . and domain-specific solutions. for example. Since the implementation is not modularized. you can defer a concern's final implementation.. it's no surprise that a few techniques Such have emerged include to mix-in modularize classes. For example. Another part of the system could set this logger to get the appropriate logging type. It also requires considerable testing effort to ensure that such implementation changes have not caused.

you'll need to change. Therein lies a problem. performance. like Visitor and Template Method.invoking visiting logic or invoking template methods -. On the other hand. let developers address some crosscutting concerns in a modularized way. because these solutions are domain specific. such the as security. The Enterprise JavaBeans (EJB) architecture. let you defer implementation. however. for the most part. and container-managed persistence. The domain-specific solution offers a specialized mechanism for solving the specific problem. CEA . developers must learn new techniques for each such solution. If you miss future crosscutting requirements. the control of the operation -. As a downside to domain-specific solutions. oblivious to the storage issues.stays with the main classes. developers addresses focus on crosscutting the business concerns logic. such as bean-data mapping to a database. administration. In this case. Thus a dilemma for system architects: How Department of Computer Science & Engg. many parts of the system. for example. Domain-specific solutions. Predicting the future is a difficult task. 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. Bean while deployment developers focus on deployment issues. bloated system. The bean developer remains. focusing too much on low-probability requirements can lead to an overdesigned. such as frameworks and application servers. However.. Further. you implement the crosscutting concern of persistence using an XML-based mapping descriptor. confusing. or possibly reimplement.Aspect Oriented Programming11 Behavioral design patterns. just as in case with mix-ins.

AOP strives to cleanly separate concerns to overcome the problems discussed above. Even for requirements known beforehand. THE FUNDAMENTALS OF AOP The scenario so far suggests that it can be helpful to modularize the implementation of crosscutting concerns. CEA .Aspect Oriented Programming12 much design is too much? Should I lean towards underdesign or overdesign? In summary." AOP represents one such method. Department of Computer Science & Engg.. the specifics needed to create an implementation may not be fully available. Researchers have studied various ways to accomplish that task under the more general topic of "separation of concerns. the architect seldom knows every possible concern the system may need to address. Architecture thus faces the under/overdesign dilemma.

OOP. data persistence. creates systems using loosely coupled. multithread safety. modularized implementations of crosscutting concerns. including business logic. View the system as a set of concerns We can view a complex software system as a combined implementation of multiple concerns.Aspect Oriented Programming13 AOP. maintainability. as security. error checking. just as a common concern's implementation in OOP is called a class. Department of Computer Science & Engg. CEA . comprehensibility. Indeed.. such authentication. and combine these implementations to form the final system. logging and debugging. and so on. traceability. Figure 1 illustrates a system as a set of concerns implemented by various modules. lets you implement individual concerns in a loosely coupled fashion. performance. in contrast. modularized implementations of common concerns. A typical system may consist of several kinds of concerns. You'll also encounter development-process concerns. and evolution ease. AOP creates systems using loosely coupled. at its core. The modularization unit in AOP is called an aspect.

Figure 2. which separates each concern. CEA .. 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. Concern decomposition: The prism Department of Computer Science & Engg. The same view also extends towards development-process concerns.Aspect Oriented Programming14 Figure 1.

. resource pooling. a storage-management concern affects every stateful business object.Aspect Oriented Programming15 analogy Crosscutting concerns in a system A developer creates a system as a response to multiple requirements. For example. and storage management. CEA . orthogonal Many (mutually independent) to each other and to the module-level requirements. administration. Each crosscuts several subsystems. a typical enterprise application comprises crosscutting concerns such as authentication. logging. Department of Computer Science & Engg. For example. We can broadly classify these requirements as core module-level system-level requirements requirements and tend system-level to be requirements. performance. System-level requirements also tend to crosscut many core modules.

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

consider only two operations: credit and debit. a processor. Currency amount) throws InvalidCardException { // Crediting logic } } Department of Computer Science & Engg. That represents a powerful paradigm shift from OOP. CardExpiredException { // Debiting logic } public void credit(CreditCard card.. interlaces different execution-logic fragments according to some criteria supplied to it. assembles an individual concern in a process known as weaving. NotEnoughAmountException. Consider the following credit card processing module: public class CreditCardProcessor { public void debit(CreditCard card. in other words. the credit card processing module doesn't know that the other concerns are logging or authenticating its operations. The weaver. Also assume that a suitable logger is available. For example.Aspect Oriented Programming17 AOP development stages AOP differs most from OOP in the way it addresses crosscutting concerns. CEA . With AOP. Weaving example The weaver. To illustrate code weaving. For brevity. let's consider a our credit card processing system example. Currency amount) throws InvalidCardException. each concern's implementation remains unaware that other concerns are "aspecting" it.

credit(CreditCard.log("Starting CreditCardProcessor. } The desired composition requires the following weaving rules.log("Completing CreditCardProcessor. public void debit(CreditCard card.. CEA . Log each public operation's completion 3. } Department of Computer Science & Engg.credit(CreditCard. expressed here in natural language (a programming language version of these weaving rules is provided later ): 1. Money) " + "Card: " + card + " Amount: " + amount). Log each public operation's beginning 2. // Debiting logic _logger.Aspect Oriented Programming18 Also. consider the following logging interface: public interface Logger { public void log(String message). 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. NotEnoughAmountException. Money amount) throws InvalidCardException. CardExpiredException { _logger. Money) " + "Card: " + card + " Amount: " + amount).

// Crediting logic _logger. } } Department of Computer Science & Engg. _logger.credit(CreditCard. CEA .. Money) " + "Card: " + card + " Amount: " + amount).println("Debiting").Aspect Oriented Programming19 public void credit(CreditCard card.log("Completing CreditCardProcessor. Money) " + "Card: " + card + " Amount: " + amount).debit(CreditCard.log("Starting CreditCardProcessor.out. Money amount) throws InvalidCardException { System.

an AOP implementation consists of two parts: a language specification and an implementation. CEA . you can to use traditional languages like C. 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. • Weaving rules specification: How to compose independently implemented concerns to form the final system. The language specification describes language constructs and syntax. Since implementation of concerns takes the form of specifying procedures. The language for specifying weaving rules Department of Computer Science & Engg. C++.Aspect Oriented Programming20 ANATOMY OF AOP LANGUAGES Just like any other programming methodology implementation. or Java with AOP.. The AOP language specification At a higher level. 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. 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.

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

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

toString(). Money amount) throwing (Exception e): publicOperationCardAmountArgs(card. amount). pointcut publicOperationCardAmountArgs(CreditCard card.. amount). thisjoin point.getSignature(). } private void logOperation(String status. } after (CreditCard card. CEA . thisjoin point.toString().getSignature().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(). Department of Computer Science & Engg. thisjoin point.)).. amount) { logOperation("Starting". Money amount): publicOperationCardAmountArgs(card. before(CreditCard card. card. amount). card. String operation. pointcut publicOperation(): execution(public * CreditCardProcessor. Money amount): publicOperation() && args(card. amount) { logOperation("Exception " + e.getSignature(). card.*(. amount) { logOperation("Completing".toString(). amount). Money amount) returning: publicOperationCardAmountArgs(card. } after(CreditCard card.

helping create a coherent evolution. Further. Since each concern's implementation is separate. it's easy to add newer functionality by creating new aspects. an architect can delay Department of Computer Science & Engg. the existing aspects crosscut them. 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. • Late binding of design decisions: Recall the architect's under/overdesign dilemma. Such an implementation produces a system with less duplicated code. CEA . modularized implementation also results in a system that is easier to understand and maintain.log(status + " " + operation + " Card: " + card + " Amount: " + amount). Further. • Easier-to-evolve systems: Since the aspected modules can be unaware of crosscutting concerns.Aspect Oriented Programming24 CreditCard card. With AOP. Money amount) { logger.. when you add new modules to a system. } } AOP BENEFITS AOP helps overcome the aforementioned problems caused by code tangling and code scattering. it also helps reduce code clutter.

On using AOP the resulting code was spread over two pages of 50 lines each.. AOP statistics 1. For example.Aspect Oriented Programming25 making design decisions for future requirements. In general. • More code reuse: Because AOP implements each aspect as a separate module. In the original FreeBSD v3.3 code. each individual module is more loosely coupled. The code is spread out over approximately 260 lines in 10 clusters in 5 core functions from two subsystems. the implementation of prefetching is both scattered and tangled. CEA . On reengineering a particular image processing program the following results were obtained 2. since she can implement those as separate aspects. you can use a module interacting with a database in a separate logger aspect with a different logging requirement. a loosely coupled implementation represents the key to higher code reuse. AOP enables more loosely coupled implementations than OOP. Department of Computer Science & Engg.

Aspect Oriented Programming26 AOP APPLICATIONS a-kernel is an effort to apply AOP techniques to operating system kernel code. QuO is a middleware framework and toolkit which includes aspect-oriented languages for developing quality of service enabled. FACET is a framework for a customizable real-time event channel that uses aspects.. CEA . Lasagne is an aspect-oriented architecture for contextsensitive and run-time weaving of aspects--prototypes have been developed in Java and Correlate. 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. adaptive distributed object applications.

org http://www.microsoft.com Department of Computer Science & Engg..research.com Microsoft MSDN site http://msdn.aosd.com http://www.aspectj.xerox.net http://www.ibm.Aspect Oriented Programming27 evolution system implemented using AOP techniques REFERENCES Aspect oriented software development sites http://www. CEA .javaworld.com IBM research site http://www. parc.

.Aspect Oriented Programming28 Department of Computer Science & Engg. CEA .