AOP Aspect-Oriented Programming

Source: Internet
Author: User
1. Introduction

The purpose of software development is to establish a model for some elements or information flows in the world. To implement software system engineering, the system must be divided into modules that can be created and managed. As a result, the object-oriented programming technology with the modular features of the system emerged. Modular object-oriented programming greatly improves the readability, reusability, and scalability of software systems. The focus of the object method is to select an object as the main unit of the module and associate the object with all the behaviors of the system. Objects have become a major element in the problem field and computing process. However, object-oriented technology does not solve the reusability of software systems in essence. When creating a software system, there are many cross-cutting concerns in real problems, such as security checks, logging, performance monitoring, and exception handling, their implementation code is mixed with other business logic code,And scattered in different places of the software (directly add the code for processing these operations to each module)This will undoubtedly undermine the "single responsibility" principle of OOP and greatly reduce the reusability of modules, which limits the maintainability and reusability of software systems. At this time, the traditional OOP design usually adopts the strategy of adding the corresponding proxy layer to fulfill the functional requirements of the system. However, such a process obviously adds a hierarchy of the system as a whole, complexity also increases, giving people a feeling of being too heavy. This produces the Aspect-oriented programming (AOP) technology. This programming mode extracts the cross-cutting focus code that is scattered across the software system, modularize and integrate it together, which further improves the maintainability, reusability, and scalability of the software.

2. Introduction to AOP

AOP: Aspect Oriented Programming for aspect programming.
Aspect-Oriented Programming (also known as Aspect-Oriented): aspect oriented programming (AOP) is currently a hot topic in software development. AOP can be used to isolate all parts of the business logic, thus reducing the Coupling Degree between each part of the business logic, improving the reusability of the program, and improving the development efficiency.
AOP is a continuation of OOP. It is short for Aspect Oriented Programming. It refers to Aspect-Oriented Programming.
Its main functions include logging, Performance Statistics, security control, transaction processing, and exception handling.
The main intention is to divide the log records, Performance Statistics, security control, transaction processing, Exception Processing and other codes from the business logic code. By separating these behaviors, we hope that they can be independent to non-guided business logic methods, so that the code without affecting the business logic will be changed.

The pre-compilation method and runtime dynamic proxy can be used to dynamically and uniformly add functions to the program without modifying the source code. AOP is actually a continuation of the GoF design model. The design model tirelessly pursues decoupling between callers and callers. AOP can be said to be an implementation of this goal.

Suppose we want to think of an application as a three-dimensional structure. The benefits of OOP are vertical cutting-in systems, which divide the system into many modules (such as user modules and article modules ), the edge of AOP is a horizontal system, which extracts the parts that may be repeated by each module (for example, permission check and logging ). It can be seen that AOP is an effective supplement to OOP.

Note: AOP is not a technology, but a programming idea. Any technology conforming to the idea of AOP can be considered as the implementation of AOP.

3. What is aspect programming?

When considering the relationship between objects and other objects, we usually think of inheriting this term. For example, define an abstract class-Dog class. Inheritance is usually used to extend functions when you identify similar classes but each class has its own unique behavior. For example, if a Poodle is identified, a Poodle is a Dog, that is, a Poodle inherits the Dog. So far it seems good, but what if I define another unique behavior that will mark it as Obedient Dog? Of course, not all Dogs are very tame, so the Dog class cannot contain obedience behavior. In addition, if you want to create a slave Dog
If the inherited Obedient Dog class is used, which position of the Poodle in this hierarchy is appropriate? Poodle is a Dog, but Poodle is not necessarily an obedient; so does Poodle inherit from Dog or Obedient Dog? None of them. We can regard tame as an aspect and apply it to any type of tame Dog. We oppose forcing this behavior into the Dog hierarchy in an inappropriate way.

4. Differences from OOP Object-Oriented Programming

Although AOP and OOP are very similar literally, they are two design ideas oriented to different fields. OOP abstracts and encapsulates the entities, attributes, and behaviors of the business processing process to achieve clearer and more efficient logical unit division.
AOP extracts the aspect of the business processing process. It faces a certain step or stage in the processing process, in order to obtain the isolation effect of low coupling between different parts in the logical process. These two design ideas are essentially different in terms of goals.
The above statement may be too theoretical. For a simple example, encapsulating a business entity such as "employee" is naturally a task of OOP/ood, we can create a "employee" class for it and encapsulate the attributes and actions related to the "employee. However, it is impossible to encapsulate "employees" with the design idea of AOP.
Similarly, the division of the Action segment "permission check" is the target domain of AOP. The encapsulation of an action through Ood/OOP is a bit nondescribable.

In other words, Ood/OOP is oriented to the noun field and AOP is oriented to the verb field.

5. Basic concepts of AOP

In object-oriented programming, classes, objects, encapsulation, inheritance, polymorphism, and other concepts are the main terms used to describe object-oriented ideas. Similarly, in Aspect-Oriented Programming, there are also some basic concepts:
Jointpoint: a specific point in the execution of a join program. Typical links include calling a method, executing a method itself, class initialization, and object initialization. A join point is one of the core concepts of AOP. It is used to define where the program joins new logic through AOP.
Pointcut: A pointcut is used to define a set of links for a notification to be executed at that time. By defining the entry point, We can precisely control the components in the program to receive notifications. As mentioned above, a typical join point is method call, and a typical starting point is the set of method calls for a class. We usually set up a complex entry point to control when the notification is executed.
Advice: the code that runs at a specific link is called "notification ". There are many types of notifications, such
Before advice and after advice executed before the join point ).
Aspect (aspect): the combination of notification and entry point is called aspect. Therefore, aspect defines the logic that should be included in a program and when the logic should be executed.
Weaving: weaving is the process of actually adding aspects to the program code. For the static AOP solution, weaving is completed at compilation, usually adding a step during compilation. Similarly, the dynamic AOP solution is dynamically woven when the program runs.
Target: if an object's execution process is modified by an AOP, it is called a target object. The target object is also known as the notification object.
Introduction: You can add new methods or attributes to an object to change its structure. Even if the class of the object does not implement an interface, you can also modify it to make it an implementation of this interface.

Static and Dynamic: The difference between static AOP and dynamic AOP mainly lies in the time when and how it is woven. Most of the earliest AOP implementations were static. In static AOP, weaving is a step in the compilation process. In Java terminology, static AOP performs the weaving process by directly operating on bytecode, including modifying code and extending classes. Obviously, the program generated by this method has good performance, because the final result is a common Java bytecode, and no special skills are needed at runtime to determine when to execute the notification. The disadvantage of this method is that if you want to modify the aspect, you must recompile the entire program even if you just add a new join point. Aspectj
It is a typical example of static AOP. Unlike static AOP, dynamic AOP is dynamically woven at runtime. The implementation varies depending on how the organization is completed. Spring AOP sets up a proxy and then executes the notification when appropriate. One weakness of dynamic AOP is that its performance is generally inferior to that of static AOP. The main advantage of dynamic AOP is that it can modify all aspects of the program at any time without re-compiling the target.

5.1 cross-cutting technology

"Cross-cutting" is a special term of AOP. It is a relatively simple design and programming technology with powerful power, especially when it is used to build loosely coupled, scalable enterprise systems. The cross-cutting technique allows AOP to traverse established responsibilities (such as logging and performance optimization) in a given programming model.

If no cross-cutting technology is used, what is the situation of software development? In traditional programs, because the implementation of cross-cutting behaviors is scattered, it is difficult for developers to implement or change these behaviors logically. For example, the code used for logging and the Code primarily used for other duties are intertwined. Depending on the complexity and scope of the problem to be solved, the confusion may be large or small. Changing the logging policy for an application may involve hundreds of edits-even if feasible, This is a headache.

In AOP, we call these actions with public logic entangled with the core logic of other modules "Crosscutting Concern )", it spans the typical responsibility boundaries of a given programming model.

5.2 cross-cutting concerns

A concern is a specific purpose, a region we are interested in, and a logical action we need. From a technical point of view, a typical software system includes some core points of attention and system-level concerns. For example, a credit card processing system focuses on lending/deposit processing, while the system focuses on logs, transaction integrity, authorization, security, and performance, many concerns-crosscutting
Concerns) -- appears in multiple modules. If the existing programming method is used, the cross-cutting concerns will jump across multiple modules, making it difficult for the system to design, understand, implement, and evolve. Compared with the preceding method, AOP can better isolate system concerns and provide modular cross-cutting concerns.
For example, a complex system is implemented by a combination of multiple concerns, such as business logic, performance, data storage, log and scheduling information, authorization, security, thread, and error check, there are also concerns in the development process, such as easy to understand, easy to maintain, easy to trace, easy to expand, etc,

1.A system consists of a group of concerns implemented by different modules, that isImplement the module as a group of concerns,

By identifying system requirements and implementation, we can divide these concerns in the module into core concerns and cross-cutting concerns. For core concerns, the modules that implement these concerns are independent of each other. They fulfill the business logic required by the system, which is related to specific business needs. But for the log, security, persistence and other concerns, they are the common needs of the business logic module, these logics are distributed in the core focus. In AOP, such modules are called cross-cutting concerns. The key to applying the cross-cutting technology of AOP is to recognize the concerns.

2. Identify concerns

If the entire module is compared to a cylinder, the focus recognition process can be described by the prism rule. The beam passing through the prism (as required) can be illuminated everywhere in the cylinder to obtain different colors of the beam, at last, different concerns are identified.

1). Focus recognition: prism rule ,:

Among the identified concerns, Business Logic is the core concern. It calls Security, Logging, Persistence, and other cross-cutting concerns.

Public class businesslogic {public void someoperation () {// verify security; securtity concerns; // logs recorded before execution; Logging concerns; dosomething (); // Save the data after the logical operation; persistence concerns; // The execution end log; Logging concerns ;}}

3. weaving the cross-cutting concerns into the core concerns

The purpose of AOP is to separate cross-cutting concerns such as logging from the businesslogic class. The AOP technology can be used to encapsulate related cross-cutting concerns to form a separate "aspect ". This ensures the reuse of cross-cutting concerns. Because the businesslogic class no longer contains the logic code of the Cross-concern, to call the cross-concern, you can use the cross-concern technology to intercept messages of relevant methods in the businesslogic class, such as the someoperation () method, then these "aspect" are woven into this method. Weaving the cross-cutting concerns into the core concerns,

By using the AOP technology, the design of the entire system is changed. At the beginning of analyzing system requirements, the idea of AOP is used to separate core points of concern and cross-cutting concerns. After implementing the general logic of cross-concern such as logs, transaction management, and permission control, developers can focus on their core concerns and focus on solving their business logic. At the same time, the functions provided by these encapsulated cross-cutting concerns can be used to restore all parts of the business logic to the maximum extent, without the need for special coding by developers, it also does not affect the specific business functions because of the function of modifying the cross-concern.

6. AOP practices

6.1 JAVA practices

In web program development, we know that because of the stateless HTTP protocol, we usually need to save the user's status information in the session. In some application scenarios, you must log on to the console to continue the operation.

Traditional implementation methods:
Therefore, before performing each business operation, the traditional implementation method adds the following logic:

protected void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  HttpSession session = request.getSession(); if(session.getAttribute("user")==null){     request. getRequestDispatcher("login.jsp").forward(req,resp);     }        doSpecialBussinessLogic(); }

The logic implemented in this way requires the programmer to follow the above methods in the places where the login check should be implemented. This will inevitably lead to a lot of code duplication and confusion. Here, the login check logic is a non-main logic, and our main logic is dospecialbussinesslogic (). The confusion between the main logic and the non-main logic is a major limitation of traditional programming methods.

Implemented Using AOP technology:

The emergence of AOP provides a good solution for the above problems. The following is the implementation of the login check logic completed with aspectj:

  public aspect LoginCheckAOP {        pointcut loginCheck(HttpServletRequest req, HttpServletResponse resp):  (execution(void *..*Action.doPost(HttpServletRequest, HttpServletResponse))) && args(req,resp);     public before(HttpServletRequest req, HttpServletResponse resp) : loginCheck (req,resp) {  HttpSession session = request.getSession(); if(session.getAttribute("user")==null){     request. getRequestDispatcher("login.jsp").forward(req,resp);     } } } 

We define a logincheckaop name. The aspectj compiler automatically inserts the code of the login check logic into the desired place by name matching. Using the AOP method for login check is better than manually inserting the check code where needed.
• All functional code to be checked must be placed in one (logincheckaop) Place.
• It is easy to insert and delete check code. You can easily implement different check aspects without modifying other code.
• Check logon wherever necessary, even if new methods or classes are added. This can eliminate human errors. At the same time, we know that all the login check code has been deleted, and nothing will be ignored when we delete it from the build configuration.
• There is a reusable aspect that can be applied and upgraded.

6.2 PHP practices

Currently, PHP does not have a complete built-in implementation of AOP. Although runkit is available, it remains in the PECL project in Beta state, it is estimated that it will not be the default setting of PHP for a long time. So is it because AOP is destroyed in PHP? Of course not, because we have magic methods such as _ Get () ,__ set () ,__ call, rational use of these methods can provide us with a certain degree of "quasi-AOP" capabilities. The reason is that it is quasi-AOP because it is far-fetched from implementation alone, however, from the perspective of the effect, some of the functions of AOP are implemented. Although the implementation method is not perfect, it is enough for general use.

<? PHP/*** business logic class in an application **/class target {public function foobar () {echo 'business logic <br/> ';}} // class AOP {private $ instance; public function _ construct ($ instance) {$ this-> instance = $ instance ;} public Function _ call ($ method, $ PARAM) {If (! Method_exists ($ this-> instance, $ method) {Throw new exception ("Call undefinded method ". get_class ($ this-> instance ). ": $ method") ;}// pre-enhancement $ this-> before (); $ callback = array ($ this-> instance, $ method ); $ return = call_user_func_array ($ callback, $ PARAM); $ this-> after (); return $ return;}/*** pre-enhancement **/public function before () {echo 'permission check <br/> ';}/*** enhanced **/Public Function after () {echo 'logging <br/> ';}} /*** factory method **/class factory {public function gettargetinstance () {return New AOP (new target ());}} // The client calls the demo header ("Content-Type: text/html; charset = utf8"); try {$ OBJ = Factory: gettargetinstance (); $ obj-> foobar ();} catch (exception $ e) {echo 'caught exception: ', $ e-> getmessage ();}

The built-in magic method _ call of PhP5 is used to implement AOP. The only drawback is that the client object of the Instance needs to be added to the AOP class, and the returned object is the object packaged by AOP. Therefore, get_class may be in trouble.

For example, the client uses the getbizinstance () method to think that the obtained object is target, but in fact it obtains a target packaging object AOP. In this way, if the client performs some operations such as get_class () such operations related to the object type will cause errors. Of course, in most cases, the client does not seem to do similar operations.

As we mentioned in the proxy mode, this is actually a dynamic proxy mode.

We use
Example of how to implement method call interception using runkit extension:

/*** A business logic class in the application **/class target {public function foobar () {echo 'business logic <br/> ';}} runkit_method_rename ('target', 'foobar', '# foobar'); runkit_method_add ('target', 'add', '$ A, $ B ', 'echo "before call \ n"; $ ret = $ this-> {"# foobar"} ($ A, $ B); echo "after call \ n "; return $ ret ;');

Some people also use the inheritance method to implement it:

<? Php // business logic class AOP {private $ instance; public function _ construct () {} public function _ call ($ method, $ param) {if (strchr ($ method, 'aop _ ') {$ method = str_replace ('aop _', '', $ method); if (! Method_exists ($ this, $ method) {throw new Exception ("Call undefinded method ". get_class ($ this ). ": $ method") ;}}// pre-enhancement $ this-> before (); $ callBack = array ($ this, $ method ); $ return = call_user_func_array ($ callBack, $ param); $ this-> after (); return $ return;}/*** pre-enhancement **/public function before () {echo 'permission check <br/> ';}/*** enhanced **/public function after () {echo 'logging <br/> ';}} /*** business logic class in an application **/class Target extends AOP {public function foobar () {echo 'business logic <br/> ';}} // The client calls the demo header ("Content-Type: text/html; charset = utf8"); try {$ obj = new Target (); $ obj-> Aop_foobar ();} catch (Exception $ e) {echo 'caught exception: ', $ e-> getMessage ();}

This has obvious disadvantages:

1) strict restrictions. If you need to enhance the method name, you need to add the AOP prefix.
2) If the target class has inherited another parent class, it cannot inherit the AOP class.
3) To implement AOP, a very important premise is that the source code cannot be significantly penetrated. The enhanced target object here must inherit the AOP class, which will undoubtedly intrude into the object.

In addition to the above implementation method, we can use the configuration file to configure which focus code is enhanced to the entry point of the target object.


7. Conclusion

Aspect-oriented programming is a new technology that inspires software developers and is used to find new modular features in software systems. Aspect-oriented programming is a supplement to object-oriented programming technology. There is no competition between them. In fact, they complement each other in software development. As a new programming technology, Aspect-Oriented Programming has bright application prospects.


This article summarizes online materials, including Baidu encyclopedia AOP Baidu Library: Research and Practice of Aspect-Oriented Programming Technology


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.