Académique Documents
Professionnel Documents
Culture Documents
CONTENTS
Introduction ................................................................................................................................ 3 The Technical Problem .............................................................................................................. 4 Cross-Cutting Concerns Common Cross-Cutting Concerns The Effect of Cross-Cutting Concerns A Framework for Cross-Cutting Behaviors 4 4 4 5
Existing Solutions ...................................................................................................................... 6 Dynamic Proxies Functional Programming Code Generation Meta-Programming 6 6 6 6
Aspect-Oriented Programming: A Better Solution .................................................................. 7 Overview of AOP The History and Evolution of AOP 7 8
The Benefits of AOP................................................................................................................... 9 Lowers Costs by Reducing Lines of Code Decreases Defects Eases Implementation of Quality Assurance Improves Maintainability Improves Teamwork 9 9 9 9 10
PostSharp: the Leading AOP Framework for .NET .................................................................. 14 PostSharp Technology PostSharp Features About SharpCrafters Featured Customers 14 14 15 16
Page 2
INTRODUCTION
For years, software engineers have struggled with the question of how to structure their code in order to maximize reuse and reduce defects. While traditional object-oriented programming (OOP) provides a solid framework for code organization, it breaks down when developers must implement features that cut across the entire system, such as logging and transaction handling. The usual methods for implementing such cross-cutting functionality lead to unnecessary code duplication, an increase in product bugs, and a decrease in both quality and time to market. Aspect-Oriented Programming (AOP) adds a high level of reuse to the traditional OOP framework, with minimal impact on existing code bases. Aspect-Oriented Programming delivers:
y y y
a decrease in development costs and software delivery time; a reduction in software defects; and an increase in application maintainability.
The following paper demonstrates these benefits in detail, and demonstrates how two companies successfully implemented AOP: Siemens Healthcare using the open-source AspectJ framework; and FullArmor, using the PostSharp framework from SharpCrafters. AOP
Page 3
1.
Logging. Developers often need to see the parameters fed to a method as it is executing and therefore need to add code to a large number of places.
2.
Security Auditing. Legal requirements and professional standards frequently demand that a software system write a record of all of its business transactions to a secure database store. This store may be audited by an independent auditing agency, a governmental body, or a court-appointed delegate.
3.
Transactions. Modern applications need the ability to roll several discrete operations into a single unit of work that can be committed as a whole, or rolled back entirely if any part of the operation fails to complete.
4.
Multithreading. Coping with several threads in an application typically requires code for thread dispatching and locking of shared resources a common cross-cutting behavior that has no direct relation to the underlying business logic.
5.
User Interface. Domain objects must typically implement several services to support rich user interfaces. Change notification and undo/redo are the most common; each requires code to be added in every object property.
1.
The number of lines of code increase. Cross-cutting concerns tend to accumulate: a business logic method that ought to be focused on calculating shipping for an online order may end up saddled with boilerplate code dedicated to creating an audit trail, authenticating the user, notifying the UI that a change has occurred, and executing its task on a worker thread.
2.
The number of defects in a feature is proportional to the size of the component. [Eaddy 2008]
An enormous amount of code is duplicated, as these boilerplate calls are often copied and pasted into new methods, which can lead to duplication of bugs and increases the
Page 4
difficulty of refactoring the cross-cutting concerns. In other words, OOP applications end up committing one of the very evils that OOP was designed to prevent: code duplication.
3.
Business logic code becomes entangled with cross-cutting code, making it harder to find the actual parts of the routine dedicated to implementing business rules. This makes applications harder to understand, debug and modify.
4.
Business logic code is tightly coupled to cross-cutting concerns. If a change to transaction handling requires a change to the public interfaces of the transaction handling component, then potentially all of the code that uses that component must change as well.
The end result of this approach to cross-cutting concerns is a code base that is hard to author, hard to maintain, and hard to debug. A study published in IEEE Transactions on Software Engineering [Eaddy, 2008] demonstrated that the number of defects in a feature is correlated to two factors:
1. 2.
As a feature becomes more scattered through the code base, the odds that it will suffer from more defects increase dramatically. [Eaddy 2008]
the number of lines of code implementing that feature; and the scattering of that feature throughout numerous source code artifacts.
The study, based on the analysis of three widely used open-source projects, also showed that cross-cutting concerns whose implementation is always very scattered have more defects than classical business features. Using a rank-order correlation coefficient, the authors found a strong correlation between a feature's bug count and that feature's diffusion across multiple classes and methods. "Crosscutting concerns" in traditional software, noted the researchers, "are hard to find, understand, and work with."
y y y y
adding cross-cutting concerns with little or no modification to existing business logic code; applying these behaviors to multiple methods, classes, or even namespaces and assemblies with minimal additional code; enhancing cross-cutting logic without the need to revise code in the business object; eliminating redundant boilerplate code that must be copied from method to method.
Page 5
EXISTING SOLUTIONS
Besides AOP, several other frameworks that were originally designed for other purposes have been recruited to address the problem of cross-cutting concerns. Each has its strengths, but because none were originally designed to address the challenges posed by cross-cutting concerns, each also possesses significant shortcomings.
Dynamic Proxies
A proxy is a common design pattern in which a class operates as a gateway to one or more other classes. A dynamic proxy is a class generated on demand by a framework. Because they are generated on-the-fly, dynamic proxies can contain additional dynamic behaviors to objects, such as logging, or multi-threading in other words, cross-cutting behaviors.
Dynamic proxies aren't flexible enough to implement all types of cross-cutting behaviors on all types of classes. Dynamic proxies also require special methods of instantiation, encourage the alteration of the architecture to conform to the limitations of dynamic proxies, and lack direct IDE support. While dynamic proxies provide some of the benefits of AOP, they fall far short of delivering on its full promise.
Functional Programming
Functional programming has become more popular with the addition of higher-order functions and PostSharp enables me to achieve things unobtrusively where other frameworks are large, ungainly, intrusive, slow, and require me to alter my architecture. As a past user of other AOP systems I am convinced there is no better system out there right now.
Andrew Matthews, Application Architect at Premier Technologies
other functional language constructs to C#. In a functional paradigm, a function is itself an object, which makes it easy to compose a family of functions together. Functional programming has been used with some success to address some crosscutting concerns such as transaction management or exception handling. However, this approach has significant drawbacks for the majority of crosscutting concerns:
1.
Developers cannot automatically pass context from the caller to the aspect code. Tracing of code execution, for example, cannot be implemented with the functional approach.
2.
Developers must modify the code of every function to which they wish to introduce crosscutting behavior.
Code Generation
Every developer who has used an IDE is familiar with the code generation paradigm, in which UI gestures or models, such as data schemas, are converted into executable code. Visual Studio and the .NET Framework define several components that attempt to turn such cross-cutting behaviors as multithreading into a matter of code generation. This is of only limited effectiveness, however, as it cannot be used to add new behaviors to existing code.
Meta-Programming
Meta programming, which has been made popular by dynamic languages, allows programs to change their behavior extensively at both runtime and build time. AOP is a specific case of meta-programming. However, AOP operates at a higher level of abstraction. Meta programming is powerful, but complex to learn and implement. Developers who have sought to implement meta-programming as a comprehensive solution to the problem of cross-cutting have found themselves writing their own aspect-oriented framework.
Page 6
1.
Encapsulating the cross-cutting concern into a source code artifact called an aspect. In OOP frameworks, the aspect is generally a class that expresses the implementation pattern and defines new behaviors. An aspect describes a program transformation and adds a new requirement to the code, such as making a method execute in a transaction. [Serializable] public sealed class TransactionScopeAttribute : OnMethodBoundaryAspect { public override void OnEntry(MethodExecutionArgs args) { args.MethodExecutionTag = new TransactionScope(); } public override void OnExit(MethodExecutionArgs args) { ((TransactionScope)args.MethodExecutionTag).Dispose(); } public override void OnSuccess(MethodExecutionArgs args) { ((TransactionScope)args.MethodExecutionTag).Complete(); } }
2.
Applying the aspect to target artifacts in source code. Aspects are applied to the target artifacts at join points, or points of program execution. A typical join point is before or after the execution of a method. Ideally, this application of aspects to join points involves using some specification such as code annotations, or a configuration file that involve no or minimal changes to the targeted source code. Join points can also be designated using pointcuts, which are complex queries on the underlying code base. Most AOP frameworks support applying aspects using some form of declarative programming a form of programming syntax that expresses a programmer s intention without execution logic or control flow. In Microsoft s .NET Framework, declarative programming is implemented using attributes. [TransactionScoped] public int CreateOrder( Order order, IList<OrderLine> orderLines ) { }
Page 7
(http://www.springsource.com/), which replaced the much more complex J2EE as the de facto standard for Java enterprise architecture. SpringSource, the company behind the Spring Framework, has enjoyed enormous commercial success: after hiring many of the original AspectJ developers, it was acquired for $400 million USD by VMWare. Since 2003, most Java application servers have added built-in support for AOP. AOP extensions have been developed for C++, Ruby, PHP, SAP's ABAP language, and even COBOL. PostSharp is the leading AOP framework in the Microsoft ecosystem. Its development started in 2006, and the first stable release was reached in 2007. Several Microsoft products, such as Windows Communication Framework (http://msdn.microsoft.com/en-us/netframework/aa663324) and ASP.NET MVC (http://www.asp.net/mvc), provide a subset of AOP features, but Microsoft has always been reluctant to use the term aspect-oriented programming, preferring the terms filters or behaviors instead. The advent of AOP has also given rise to aspect-oriented software development (AOSD). The relationship between AOP and AOSD is similar to the relationship between OOP and objectoriented analysis and design (OOAD): AOSD brings aspect orientation to the analysis and design phases of the software development process.
Page 8
Decreases Defects
As demonstrated by [Eaddy, 2008], the number of defects in a feature increases with both the number of lines used to implement the feature, and the degree to which the feature s code base is scattered across the system. Aspects address both concerns. Code is reduced and consolidated by isolating the aspect into a single location. The use of declarative syntax for applying the aspect to code artifacts eliminates the amount of boilerplate code that must be injected throughout the system versions. Although aspects can also contain defects, it is much easier to fix a bug once in the aspect class than in every of the thousands of methods in which it is applied, as is the case when the behavior is implemented without AOP. code that itself may have contained defects, or otherwise required revision in subsequent
Improves Maintainability
The initial development of an application represents only a fraction of its lifetime cost. The application's evolution occurs during maintenance. As Meir Lehman noticed early, software systems evolve dramatically after their initial release, and grow in complexity over time [Lehman, 1980]. During the maintenance phase, developers spend as much time reading code as they do writing it [LaToza, 2006; Ko, 2006]. Analyzing the source code is necessary in order to understand the changes made by other members of the team. It also becomes necessary for developers to reeducate themselves on the structure of the system as time progresses, and their memory of the
Page 9
initial development fades. Turnover is also a factor: fresh-blooded team members with no prior knowledge of the system must rely primarily on the source code to educate themselves about its operation. Teams that minimize code scattering of cross-cutting concerns make it easier for developers to find the code affected by a change in a feature. AOP enables developers to keep business code clean by moving technical concerns out of business code. A new developer reading source code that employs AOP doesn't have to differentiate between business logic and cross-cutting concerns, as the cross-cutting behaviors are neatly isolated into aspects. Besides making code easier to read, AOP increases cohesion within classes. Some studies [Greenwood, 2007] have shown that AOP applications begin with better cohesion, and maintain more stable cohesion within their classes over subsequent versions when compared with traditional OOP applications.
Improves Teamwork
One of the most cited benefits of AOP is improved collaboration within development teams. Because AOP provides a cleaner separation of concerns in complex applications, it enables teams to isolate their architectural patterns from business logic code. This frees more team members to fuse deep technical knowledge with their intimate knowledge of the company s business processes. For example, a developer with expertise in multithreading could develop multithreading aspects, while another developer with auditing expertise could develop auditing aspects. Their colleagues can use these components to add multithreading and auditing to the application s business logic. Consequently, new team members must study a smaller code base before starting to be productive.
When I started to use PostSharp intensively in my project, my code became much simpler and much more homogeneous. At that time, my team was mainly composed of junior developers. Giving them code that was much simpler that was just business logic made it much easier for them to maintain.
Pierre-Emmanuel Dautreppe Architect at Thales Information Systems
Page 10
CASE STUDIES
Siemens, Healthcare Industry
Anyone looking for proof that AOP can scale to large applications need look no further than Siemens Healthcare [Wiese, 2005]. The company s US division decided to implement AOP on a large-scale hospital information system being built by 400 developers spread across four countries.
Aspects
Siemens used AOP in four principal areas:
y
Our ultimate ambition is to see the entire range of non-functional requirements, Quality of Service monitoring, authorization and authentication, performance monitoring, distributed caching and message routing, implemented using AOP.
Daniel Wiese and Regine Meunier, Siemens AG [Wiese, 2005]
Architectural validation. Siemens used pointcuts to tie in code that validated the multiple layers and separation of concerns required by their complex Service-Oriented Architecture (SOA). Its validation aspects ensured during development that each layer could only make calls to specific other layers (e.g., only the business layer could access Web Services), and that certain APIs could only be called from specific layers (e.g., the Java Persistence API could only be accessed from the data layer). Caching. Since the SOA was developed by multiple agile programming teams, each team ended up coding its own solution to common cross-cutting concerns. A code review revealed that the SOA contained multiple, independent implementations for caching of recently used pages and data objects; some developers rolled their own solutions, while others employed third party libraries and open source solutions. The Siemens team centralized all caching behavior into aspects, greatly reducing the application s code complexity. By implementing a global caching system, Siemens obtained global control and monitoring of the application s memory consumption. The use of aspects also cut down on the extraneous instantiation and invocation code (so-called glue code ) that would have been necessary if the team had implemented a caching object using traditional OOP. Auditing. Health care industry applications require strict auditing. Siemens employed aspects to facilitate auditing. By implementing aspects that ensured that the auditing framework received an auditing event after a method was called, Siemens was able to use AOP to verify that all applicable methods were auditing their execution. These auditing checks were only used during development, and were easily disabled during production builds. Performance monitoring. Finally, Siemens used aspects to trace the execution time of service calls across its multi-layered system. Aspects simplified the task of gathering a single set of performance statistics from which the team could generate a single report. The use of aspects also made it easier to remove performance monitoring code from the production release.
Rollout of AOP
Siemens Healthcare skillfully rolled out AOP to its developers in several stages. Relying on the advice of AOP expert Ron Bodkin, the company rolled out AOP in four stages:
1. 2. 3. 4.
Learning and experimentation; Solving real-world problems; Integration into core development; and Sharing with others.
Page 11
AOP supports the achievement of a specific goal of agile development: to handle cross-cutting functionality from an overall view.
Daniel Wiese and Regine Meunier, Siemens AG [Wiese, 2005]
In stage 1, the company appointed an AOP evangelist who worked closely with the project s technical leads, and who encouraged individual team members to experiment and familiarize themselves with aspects. Stage 2 centered on the rollout of an architectural validation platform built using AOP. This provided a low-cost way to validate the use of AOP itself, and to give developers a way to familiarize themselves somewhat with AOP concepts before having to dive into developing or applying aspects themselves. At stage 3, the team decided to implement caching as an initial means of exposing the application of aspects to developers. It also marked the company s incorporation of aspects into the global build system. After this, the project progressed into stage 4, where developers could share their experiences with aspects, and discuss ways to utilize the technology going forward.
FullArmor, IT Industry
FullArmor (http://www.fullarmor.com/) is a software and Software-as-a-Service (SaaS) vendor specializing in endpoint management and endpoint security products for the Windows platform. Its software offerings focus around scalable management solutions for Windows application delivery and installation, policy management, profile virtualization, and cloud data management. FullArmor maintains a heterogeneous family of software applications using multiple technologies and deployment environments. Its application code runs on the server using ASP.NET, as well as in the browser using Microsoft Silverlight. Further, FullArmor's Web server applications operate both on dedicated physical Web servers as well as in cloud computing environments, such as Microsoft's Windows Azure and Amazon's EC2. Any technology it adds to its software base must be able to function with high quality and high performance across all these environments. FullArmor has integrated PostSharp from SharpCrafters into three of its key products: AppPortal, PolicyPortal, and ProfilePortal. These three applications and their shared components comprise approximately 1.2 million lines of code.
Aspects
FullArmor has used PostSharp to simplify implementation of a range of cross-cutting features, including:
y y y y y y y
Tracing. Extensive logging was especially important in phases of the project, when the target platform (Windows Azure) was still in early testing phases. Resource monitoring. FullArmor used aspects to meter consumption of resources across the system, including devices, users, and network bandwidth. Build-time validation. WCF require interfaces and methods to be annotated with specific custom attributes. An aspect emitted a build-time error when this protocol was not respected. Transaction handling. Declarative management of database transactions. Exception handling. Application policies required to automatically retry an operation in response to certain exceptions, or ignore exceptions that don t indicate a critical failure. Security. Granting or demanding authorization in response to specific method calls. Caching of high-demand data and objects.
Page 12
Rollout of AOP
The technology was well received by the company s developers, and the results have been roundly beneficial. Developers and product managers at the company report that PostSharp has enabled them to separate cross-cutting concerns such as logging and security from their middle tier Web Services. Like many large companies, FullArmor uses this easy separation of concerns to divide its development team according to competencies: the architecture team focuses on creating aspects that implement cross-cutting behavior, which the business development team can then associate with join points across the business layers of FullArmor's application suite.
"[PostSharp] makes it easier to see what's relevant, and of course, that makes [the code] easier to maintain."
David Gressett, Product Manager and Chief Architect at FullArmor
Page 13
PostSharp Technology
PostSharp relies on post-compilation, also called static weaving or MSIL/bytecode rewriting, which enhances the output of the compiler by producing a new executable program that includes additional behaviors added by aspects. PostSharp rocks! And I mean that as someone who is doing AOP for a long while, and has implemented some not insignificant parts of Castle DynamicProxy. Leaving aside the amount of power that it gives you, PostSharp simplicity is simply amazing, wow!
Oren Eini (Ayende) NHibernate, Castle, and Rhino Mocks contributor
All compilers targetting the .NET platform emit programs expessed in a binary language called Microsoft Intermediate Instruction Language (MSIL). MSIL is extensively documented in the ECMA335 standard specification, and has proved very stable. Used in some Microsoft products (e.g. code coverage in Visual Studio Team System, Code Contracts), post-compiling techniques are fully supported and do not use any undocumented feature. Only post-compilation technology supports all of the features required by robust AOP frameworks high expressiveness, no impact on business logic, robust aspect composition, build time validation, IDE integration, and a gentle learning curve.
PostSharp Features
High expressiveness
Although most frameworks support simple features, such as method interception, only a few frameworks including PostSharp implement the concepts of pointcuts and advices in order to implement most complex design patterns. PostSharp allows developers to express aspects using the following primitives:
y y y y y
Execute code when a method is entered or is exited with success or failure. Intercept calls to a method, a field, a property, or an event. Introduce an interface, a property, or an event to a class. Add custom attributes to any code element. Add managed resources to assemblies.
Page 14
y y
Declaratively, through custom attributes and multicast custom attributes. Several elements of code can be targeted in a single line of code. Imperatively, by executing C#/LINQ code at build time to evaluate queries of any complexity over assembly metadata (System.Reflection).
While other frameworks require developers to use special factory methods instead of constructors, or make most methods virtual, PostSharp never requires developers to change their code.
Build-time validation
The earlier an error is detected, the cheaper it is to fix. PostSharp validates aspects at build time, and enable developers to write code that checks that the aspect has been applied to an expected element of code. There errors are shown in the IDE. Without build-time validation, errors are discovered in later phases.
IDE integration
There are times where developers need to know all of the targets of a specific aspect, as well as which aspects are applied to a specific element of code. PostSharp s extensions to Visual Studio help answer these questions without the need to waste time on studying and debugging code. Without IDE integration, developers have to spend more time debugging, and AOP s promise of greater productivity is lost.
About SharpCrafters
PostSharp was created by Gael Fraiteur in 2004 as an open-source project. Gael progressively turned the project into a commercial product and, in 2009, founded SharpCrafters. SharpCrafters builds software for .NET developers who want to focus more on business logic and creative solutions, and less on mundane, repetitive tasks. SharpCrafters products help development teams, architects, and managers at industry-leading companies produce better quality code, and reduce development and maintenance costs.
Page 15
Featured Customers
PostSharp is used daily by thousands of professional software developers worldwide.
Page 16
CONCLUSIONS
Since the foundation of the discipline, the challenges faced by software engineering have evolved considerably. Whereas the first generation of computer programmers had to struggle with scarcity of hardware resources, today s limiting factor is the ability of individuals and teams to cope with complexity. The capacity to keep source code simple during its whole lifetime not only during its inception phase, but is one of the most important keys to success.
As any engineering discipline, software engineering learned that simplicity is achieved by pursuing a good separation of concerns. A separation of concerns is what allows designers to componentize solutions to recurring problems whether in software engineering, mechanical engineering, electrical and electronic engineering, or architecture. Although object-oriented programming (OOP) made significant progress in this direction, there is still a large category of issues that cannot be addressed appropriately using traditional programming styles: technical requirements and others features grouped under the term of crosscutting concerns. Aspect-oriented programming (AOP) is an extension of OOP and is specifically designed to address cross-cutting concerns in software development. AOP enables developers to write a formal expression of solutions to repeating problems and automatically implement them rather than manually doing so with conventional programming techniques. Just as object-oriented programming did not replaced structure programming, aspect-oriented programming is not a replacement of OOP but rather an extension of it. AOP s positive impact on software development is measurable in both controlled studies and real-world development efforts. Today, AOP is supported in most languages and platforms. AspectJ, the reference AOP implementation, is the leading tool for Java. For Microsoft .NET, PostSharp is by far the most advanced and mature framework, and has been used commercially for several years by Fortune 500 companies. The best way for teams to learn AOP is to begin with simple aspects and add them to non-critical applications. For instance, developers can use diagnostic aspects during development and remove them from the production release, all without any impact on code. Then, as developers become more confident in AOP, they can begin to add more complex aspects in more critical applications. By embracing aspect-oriented programming today, engineers are moving toward software of higher quality and lower complexity.
Page 17
WORKS CITED
[Eaddy, 2008] Eaddy M., Zimmerman T., Sherwood K., Garg V., Murphy G., Nagappan N., Aho A. (2008). Do Crosscutting Concerns Cause Defects? IEEE Transactions on Software Engineering, Vol. 34, No. 4, July/August. Available online at http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.164.7117&rep=rep1&type=pdf. Illustrations reproduced with kind permission of IEEE. [Greenwood, 2007] Greenwood P., Bartolomei T., Figueiredo E., Dosea M., Garcia A., Cacho N;. Sant'Anna C., Soares S., Borba P, Kulesza U., Rashid, A. (2007). On the Impact of Aspectual Decompositions on Design Stability: An Empirical Study. ECOOP 2007 - Object-Oriented Programming, 21st European Conference, Berlin, Germany, July 30 - August 3, 2007, Proceedings. Available online at http://eprints.comp.lancs.ac.uk/1665/. [Ko, 2006] Andrew J. Ko, Brad A. Myers, Michael J. Coblenz, and Htet Htet Aung. An Exploratory Study of How Developers Seek, Relate, and Collect Relevant Information during Software Maintenance Tasks, IEEE Transactions on Software Engineering, vol. 32, no. 12, December 2006. Available online at http://faculty.washington.edu/ajko/papers/Ko2006SeekRelateCollect.pdf [LaToza, 2006] Thomas D. LaToza , Gina Venolia , Robert DeLine. Maintaining Mental Models: A Study of Developer Work Habits. Proceedings of ICSE'06, May 20 28, 2006. Available online at http://www.cs.cmu.edu/~tlatoza/Maintaining%20Mental%20Models%20%20A%20Study%20of%20Developer%20Work%20Habits.pdf [Lehman, 1980] Lehman M., 1980. Program, Life-Cycles and the Laws of Software Evolution. Proceedings of IEEE, 68, 9, pp. 1060-1076 [Wiese, 2005] Wiese D., Meunier R. Large Scale Application of AOP in the Healthcare Domain: A Case Study. Proceedings of SIGPLAN`05, June 12-15, 2005
OTHER RESOURCES
AspectJ http://www.eclipse.org/aspectj/ http://www.eclipse.org/ajdt/ AspectJ Development Tools PostSharp
http://www.sharpcrafters.com/postsharp
Page 18