Aspect-Oriented Programming

Source: Internet
Author: User
Tags java spring framework
Matthew deiters
Thoughtworks

Applicable:
Microsoft Visual Studio
Microsoft Visual Basic

Abstract:From the perspective of practical application, this article describes how to dynamically expand the behavior of web service client applications.

Click here to download the sample code.

Content on this page
Introduction
What is aspect?
AOP: benefits and disadvantages
Beyond trace. writeline
Background implementation
Combined Behavior
How far does AOP go?
Summary


Introduction

Aspect-Oriented Programming(AOP) has been around for a long time, but has not been favored by the Microsoft. NET development community until recently. Adoption of any new technology often leads to misunderstandings about the technology and its use, and AOP is no exception. To clarify the misunderstanding of AOP, this article and the following code examples will illustrate the actual application of AOP and some common problems that can be solved by AOP. Taking an application using a Web service as an example, we will extend the object function returned by the web service by applying a new aspect to the returned object through an AOP framework. These aspects will generate an object model independently for this function, thus discontinuing from the WSDL.

Back to Top


What is aspect?

When considering the relationship between objects and other objects, we usually think of inheriting this term. For example, define an abstract class-DogClass. Inheritance is usually used to extend functions when you identify similar classes but each class has its own unique behavior. For examplePoodle, You can sayPoodleIsDog, That isPoodleInheritedDog. It seems good till now, but if another one is defined, it will be markedObedient dogWhat about the unique behavior? Of course, not allDogsAll of them are very tame, soDogClass cannot containObedienceAction. In addition, if you want to createDogInheritedObedient dogClass, thenPoodleWhich position is suitable for this hierarchy?PoodleIsDog,PoodleNot necessarilyObedient; ThenPoodleIs inherited fromDogOrObedient dogWhat about it? None of them. We can regard it as an aspect and apply it to any type of tameDogWe oppose forcing this behavior in an inappropriate wayDogIn the hierarchy.

In terms of software, Aspect-oriented programming can be applied to change the class or object behavior independently of any inherited hierarchy. Then, these aspects are applied at runtime or during compilation. Give an example of AOP and describe it. First, define four key AOP terms, which is important because I will use them repeatedly:

Joint point(Joinpoint)-clearly defined identifiable points in the code.

Cut Point(Pointcut)-a method for specifying a joint point by configuring or encoding.

Notification(Advice)-indicates a method that requires cross-cutting.

Mix in(Mixin)-Add a class instance into the target class instance to introduce a new behavior.

To better understand these terms, you can regard the joint point as a point defined in the Program Stream. A good example of a joint point is: when the Code calls a method, the point that is called is considered as a joint point. The cut point is used to specify or define the joint points to be intercepted in the Program Stream. A cut point also contains a notification that occurs when the joint point is reached. Therefore, if a cut point is defined on a specific method called, The AOP framework intercepts the cut point when the method or joint point is called, and a cut point notification is also executed. There are several types of notifications, but the most common case is to regard them as another method to be called. When calling a method with a cut point, the notification to be executed will be another method to be called. The notification or method to be called can be an intercepted method in the object, or a method in another mixed object. We will further explain the problem later.

Back to Top


AOP: benefits and disadvantages

A common misunderstanding is that AOP is interception, but this is not the case. However, it does use interception to apply notifications and composite behaviors. Some. Net code examples are as follows:ContextboundobjectIt is intercepted in an AOP flip style. HoweverContextboundobjectIt is not suitable to describe interception, because the prerequisite for using this method is that all classes to be intercepted mustContextboundobjectInheritance. ImageContextboundobjectIn this way, the prerequisite AOP method will have a negative impact on the demand. Therefore, it is regarded as a heavy method in AOP and should be avoided. A large number of "footprints" left by methods in the system may potentially affect each category and impede future changes or modifications to system functions.

I createdEncaseLightweight Framework. The term "lightweight" indicates that the system has no overall impact. Different parts of the system are still affected by AOP, but selecting a lightweight framework and applying good programming practices can reduce most of the negative problems.EncaseThe framework is used to simplify cut points, mix and aspect combinations. Developers canEncaseTo replace the configuration files (such as XML) used by most other lightweight AOP frameworks ).

The heavy-weight framework hinders the application of AOP, but the main cause is that currently almost all available AOP examples contain the following:Trace. writeline ("method entered ."). Contrary to the general view, AOP is useful for solving other problems in addition to logging, security, specification, and other such issues.

Back to Top


Beyond trace. writeline

To illustrate how to use AOP more effectively, we will create an application namedContactservice. ServiceThe set of people objects that the Web Service receives. Currently, the most common way to use web services in. NET development is to call the Web service that returns XML. This service is automatically deserialized into an object through the framework. These objects only contain data and do not contain any behavior. In. NET Framework 2.0PartialKeyword and create behavior to add functions to the objects generated by the automatic code. However, there is still a problem in reusing a specific behavior between some web services or proxy objects. As mentioned above, in most cases, shared public behaviors are contained in an abstract class, and all other classes inherit from this class. However, we cannot inherit web service objects. This opportunity demonstrates how powerful the AOP function is.

Our application is used to display contact information. At first, it was used to display information, but now some actions need to be added. To view the sample code, we need to createTheagiledeveloper. contactservice. This directory must pointTheagiledeveloper. contactserviceThe location of the project on the local computer.

NoteYou can access this project through http: // localhost/theagiledeveloper. contactservice, which is very important.

Figure1.Application screen snapshot.

The application has a view namedMainformWinform, used to display the left sideListviewThe contact object returned by the web service. When you select a contact, the first name, last name, and Web page are displayed in the text box on the right. LoadMainformIt callsServicemanagerClass to obtain contact information. BelowServicemanagerAt first glance, it seems that no value is added, but another layer is added between the form and the web service. However, its value lies in providing a location for adding new features to Web services without repeating the code. Another advantage is that it abstracts the Web Service "footprint" and removes it from the entire application.

Public Class ServiceManager    Public Shared Function GetAllContacts() As ContactService.Contact()        Dim service As ContactService.Service = New ContactService.Service        Dim contacts() As ContactService.Contact = service.GetAllContacts        Return contacts    End Function    Public Shared Sub SaveContact(ByVal contact As ContactService.Contact)        Dim service As ContactService.Service = New ContactService.Service        service.SaveContact(contact)    End SubEnd Class

ViewTheagiledeveloper. ClientProjectReference. VBFile. It is in the ImportContactserviceWsdl.exe is used to create a web reference. It automatically generates the following from the WSDL:ContactClass.

'<remarks/>    <System.Xml.Serialization.XmlTypeAttribute(_  [Namespace]:=http://tempuri.org/TheAgileDeveloper.ContactService/Service1 _ )>  _    Public Class Contact                '<remarks/>        Public Id As Integer                '<remarks/>        Public FirstName As String                '<remarks/>        Public LastName As String                '<remarks/>        Public WebSite As String    End Class

Note,ContactCurrently, the object only processes data, and we do not want to edit the code in any way. Because wsdl.exe is automatically generated for us, changes will be lost during the next generation. I want to introduce the behavior so that you can callSaveTo save the object, it is easy to useMix in.Mix inIt is a multi-inheritance replica, but it has limitations. For example, it can only be mixed into interface implementations. We useEncaseThe framework containsEncaserClass, which receives and wraps an object. The behavior of the wrapped object actually means creating a new object. In this example, it is a newContactObject, which contains the mixing and cutting points of the configuration.

To createContactYou must specify an interface to call the "save" method on the object.Isavable. The actual object isIsavableInterface. We needContactsaveTo implement this interface.

Public Interface ISaveable    Sub Save()End InterfacePublic Class ContactSave    Implements ISavable    Public Contact As ContactService.Contact    Public Sub Save() Implements ISavable.Save        ServiceManager.SaveContact(Me.Contact)    End SubEnd Class

In our applicationContactObjectContactsaveThe proper implementation location is servicemanager. We can mix in this behavior, but do not change any client code (that is, mainform), because after the application is mixed inContactAndContactsaveNewContactThe object remains the originalContactType. The following code is modified by servicemanager:GetallcontactsMethod.

Public Shared Function GetAllContacts() As ContactService.Contact()        Dim service As ContactService.Service = New ContactService.Service        Dim contacts() As ContactService.Contact = service.GetAllContacts        '//Wrap each contact object        For i As Integer = 0 To contacts.Length-1            '//Create a new instance of the '//encaser responsible for wrapping our object            Dim encaser As encaser = New encaser            '//Add mixin instance of ContactSave            Dim saver As ContactSave = New ContactSave            encaser.AddMixin(saver)            '//Creates a new object with '//Contact and ContactSave implementations            Dim wrappedObject As Object = encaser.Wrap(contacts(i))            '//Assign our new wrapped contact object '//to the previous contact objectcontacts(i) = DirectCast(wrappedObject, _  ContactService.Contact) '//Notice the wrapped object is still the same type            '//Assign the new wrapped Contact object to '//target field of the ContactSave mixed in            saver.Target = contacts(i)        Next        Return contacts    End Function
Back to Top


Background implementation

Each Framework application has a unique cutting point, notification, or method, but its purpose and concept are the same. In this example,EncaserWhen packaging an object, the actual operation is throughSystem. reflection. emitClasses in The namespace generate msil code and then create a newContactType. NewContactType derived fromContactClass, it still shares the type, but the newly wrapped object still holdsContactsaveObject reference, which is included in.Isavable. SaveIn the newContactObject. ThereforeSaveIt actually delegates the call toContactsaveObject. The advantage of doing so is that the newContactConvert an object to any interface implemented on any mixed objects.

Figure2.TheUMLCharts.

You may want to use the. NET Framework 2.0 partial classification language functionPartialClassSaveAction. This is possible, but this method is not used in this article, so that the code is backward compatible with other versions of. NET Framework 1.x. Since some language functions are available, the previous example does not need to be used normally.Mix in. HoweverMix inIt is still very valuable because it allows developers to mix reusable object behaviors. These objects can be derived from other unrelated object hierarchies, which implement the function RatioPartialClass. In usePartialWhen a keyword is used, code is added to the same class or type, but the physical location is different. The following examples show that the addition is not only specificContactClass, butFieldundoerReusable class.FieldundoerImplementedIundoableInterface, allows the modified object to restore to the original state.

    Public Interface IUndoable        ReadOnly Property HasChanges() As Boolean        Sub Undo()        Sub AcceptChanges()    End Interface

HaschangesAttribute indicates that, if a change occurs,UndoRestore an object to its original state,AcceptchangesReceives the current changes of the object, so call it at any timeUndoWill be restored to the status of the last change received. If this interface is implemented in a partial classification, you must repeatedly implement these three methods in each class that wants to include the behavior. As a pragmatic programmer, I tried to stick to the "one-time and only-once code" principle, so I never want to repeat any code. The less I copy and paste it, the better. By using ing, I can reuse the implementationIundoableOfFieldundoerObject. InServicemanagerI have added this new feature. All client code is still unknown and does not need to be changed unless you need to useIundoableInterface. ChangeMainformInContactObject, and then click "undo" to test the behavior.

Public Shared Function GetAllContacts() As ContactService.Contact()        Dim service As ContactService.Service = New ContactService.Service        Dim contacts() As ContactService.Contact = service.GetAllContacts        '//Wrap each contact object        For i As Integer = 0 To contacts.Length-1            '//Create a new instance of the encaser '//responsible for wrapping our object            Dim encaser As encaser = New encaser            '//Add mixin instance of ContactSave            Dim saver As ContactSave = New ContactSave            encaser.AddMixin(saver)            '//Add mixin instance of FieldUndoer            Dim undoer As FieldUndoer = New FieldUndoer            encaser.AddMixin(undoer)            '//Creates a new object with Contact '//and ContactSave implementations            Dim wrappedObject As Object = encaser.Wrap(contacts(i))            '//Assign our new wrapped contact object '//to the previous contact objectcontacts(i) = DirectCast(wrappedObject, _ ContactService.Contact) '//Notice the wrapped object is still the same type            '//Assign the new wrapped Contact object to target fields             saver.Target = contacts(i)            undoer.Target = contacts(i)        Next        Return contactsEnd Function
Back to Top


Combined Behavior

Mixing is just the tip of the iceberg. The feature that really makes AOP famous is the combination of mixed behavior. To use the newContactObject as an example.Isavable. SaveThe client code also needs to callIundoable. acceptchangesMethod for the next callIundoable. UndoTo the last saved change. In this smallMainformIt is easy to browse and add this object, but coding this rule is a heavy task in any system that is much larger than the user interface. You need to find all callsSaveMethod, and then add anotherAcceptchanges. In addition, when creating new code, developers also need to remember that each callSaveAdd this new feature. This will soon produce cascade effects, which will easily damage the system's stable surname and introduce some bugs that are difficult to track. The use of Aspect-Oriented Programming can combine these methods. Specify a cut point and notification.SaveMethod,ContactThe object will automatically callAcceptchanges.

In order to implement the combination in the applicationServicemanagerAdd a line of code. We are joiningFieldundoerAdd this line of code after mixing.

'//Specify join point save, execute the AcceptChanges methodencaser.AddPointcut("Save", "AcceptChanges") 

AddpointcutMethods are reloaded using several different signatures, which provides greater flexibility for specifying the cut point. We callAddpointcutReceives a string-type join name, which is expressedSaveMethod, and then receivesAcceptchangesAs the notification of execution. To check whether this works, you canFieldundoer. acceptchangesMethod andContactsave.SaveSet a breakpoint before the method. ClickMainformOnSaveThe button will intercept the joint point, and you will first interrupt to the notification-that isAcceptchangesMethod. The notification will be executed after executionSaveMethod.

This simple example shows how to add new behaviors throughout the entire application, and its functions are extremely powerful. Although this function is available, it is not only a good New Method for adding features. Among the many advantages, only a few involve code reuse, and improve the maintainability of the system by simplifying the system evolution brought about by new requirements. At the same time, misuse of AOP will cause significant negative effects on the maintainability of the system, so it is important to understand the timing and methods of using AOP.

Back to Top


How far does AOP go?

The Application of AOP to most large systems or key production systems is not yet completely mature, but with the improvement of language support, the application of AOP will be easier. In addition, increasing support is also a new software development example, for example, using a software factory for Aspect-Oriented Programming. Currently, there are several available AOP frameworks in the. NET field. Each framework has its own method, positive attributes, and negative attributes.

Encase-The encase framework in this sample code is just a tool that helps you quickly understand and run AOP and understand the concepts behind AOP. Encase can be added to an object separately during runtime.

Aspect #-A cli-based AOP joint compatibility framework that provides built-in languages for declaration and configuration.

Rail-The rail framework is applicable to the JIT class of virtual machines.

Spring. net-A. Net version of the popular Java Spring framework. AOP will be implemented in the next version.

EOS-It is used for an aspect-oriented extension of C.

Back to Top


Summary

The purpose of this article is to describe a new method for applying AOP more effectively than conventional logging or security instances. Correct use of AOP can bring many advantages, and even help you complete the task that cannot be completed by conventional programming options. I strongly recommend that you search for a large number of available resources on the Internet to guide the application of AOP methods and scenarios.

About the author

Matthew deiters is enthusiastic about software development. He is a consultant at thoughtworks. He has helped develop enterprise-level systems for the financial and insurance industries through. NET Framework. He valued XP programming and TTD methodology and believed that most human problems could be solved through design patterns and/or good unit tests. You can contact Matthew through his personal web space:Www.theagileapps.com.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.