Learn about AOP (Part 1)
Separate software concerns with aspective programming
Summary
Most software systems include several focuses spanning multiple modules. Implementing these concerns with object-oriented technology will make the system difficult to implement, difficult to understand, and is not conducive to software evolution. The new AOP (angular programming method) utilizes modularization to separate the focus of the transverse multi-module in the software. Using AOP, you can create systems that are easy to design, easy to understand and maintain. In addition, AOP can bring higher output, better quality, better scalability, this article is the first chapter in this series, introducing the concept of AOP and what it solves.
Author: Ramnivas Laddad
A focal point is a specific purpose, an area we are interested in. From a technical perspective, a typical software system contains some core focus points and system levels. For example, the core focus of a credit card processing system is to borrow / deposit processing, and the system-level focus is the log, transaction integrity, authorization, security and performance issues, many attention points - we Call it cross-cutting points - will appear in multiple modules, using an existing programming method, cross-cutting points will cross multiple modules, the result is to make the system difficult to design, understand, implement, and evolve.
AOP (angular programming method) can be better separated by the above-mentioned method to provide modular cross-cutting points.
In this article - about the first chapter of the three articles of AOP, I will first explain the cross-cut concern in some software systems that are secondary complexity, and then I will introduce the core of AOP. Concept and demonstrate how AOP solves the problem of cross-cut concerns.
Evolution of software programming methods
In the early stage of computer science, developers use direct machine-level code to program, unfortunately, programmers have more time to consider a specific machine's instruction set rather than the problem that needs to be solved in hand. Slowly turn to use a high-level language that allows for a certain abstract abstraction to the underlying machine. Then it is structured language, we can break the problem into some necessary processes to complete the task. However, with the increase of complexity, we need more suitable techniques. Object-oriented programming method (OOP) allows us to see the system as a group of people working with each other. Class allows us to hide the implementation details. Multi-state provides public behavior and interfaces for related concepts, and allows specific components to change specific behaviors without accessing the basic implementation.
The programming method and language determines our way to communicate with your computer. Each new methodology proposes a new method of decomposing: machine code, pseudo code, process and class. Each new methodology makes the mapping from the system requirements to programming concepts more natural. The development of programming methodology allows us to build a more complex system. This sentence is also right, we can build more complex systems because these technologies allow us to deal with this complexity.
Most software items are now selecting OOP programming. Indeed, OOP has demonstrated its ability to handle general behavior, but we will see it after a while (maybe you have felt), OOP can't handle more than a few - often is not related - module behavior, In contrast, AOP fills this gap, it is likely to be the next milestone for programming methodology.
Watch the system as a batch of attention
We can regard a complex system as a combination of multiple attention points, a typical system may include several concerns, such as business logic, performance, data storage, log, and debugging information, authorization, Safety, thread, error check, etc., there is also a concern in the development process, such as easy to understand, easy to maintain, easy to track, easy to expand, etc., Figure 1 demonstrates a group of attention to a batch of concerns implemented by different modules to form a system. Figure 1. Transfer the module as a batch of attention
Figure 2 The demand is higher than the light passing through the three prism. We make the demand light to identify the tris prism through the point of interest, which will distinguish every payment point, the same method is also applicable to the development phase.
Figure 2. Point decomposition: three prism rules
Crossing point in the system
Developers build a system to meet multiple needs, we can roughly classify these needs as core modular needs and system level needs. Many system-level demand generally is independent of each other, but they generally cross a number of core modules. For example, a typical enterprise app contains many cross-cut points, such as validation, logs, resource pools, system management, performance and storage management, etc., each payment point involves several subsystems, such as storage management attention Click to affect all stateful business objects.
Let us look at a simple, but concrete example, consider an implementation framework that encapsulates the business logic:
Public Class SomebusinessClass Extends OtherBusinessClassClass (/) Core Data Members / Other Data Members: Logistics, Guaranteed flag bits of data integrity, etc. // Overload base class PUBLIC VOID PerformsomeOperation (Operationinformation Info) {// Security Authentication / /
Check if the incoming data meets the protocol // lock object to ensure that the data integrity when other threads is accessed // checks whether the cache is the latest information // record operation start execution time // Perform the core operation // record operation Completion time / / Unlock objects} // Some similar operations public void save (PersitanceStorage ps) {} public void loading (PersitanceStorage PS) {}}
In the above code, we noticed three issues, first, other data members are not the core attention point of this class, the second, PerformsomeOperation () implementation has made many core operations, it is to handle logs, verification Some peripheral operations such as thread safety, protocol verification, and cache management, and these peripheral operations are also applied to other classes, third, Save (), and LOAD (), whether the persistence operation performed by the LOAD () is clearly clear.
Hespered concerns.
Although cross-cutting points will span multiple modules, current technologies tend to use one-dimensional methodology to handle this demand, and forced to limit the implementation of the corresponding demand in a single-dimensional space. This one-dimensional space is the core module-level implementation, and the implementation of other needs is embedded in this dominant space. In other words, the demand space is a n-dimensional space, and the real space is a one-dimensional space, this mismatch leads to this mismatch Worse demand to realize mapping
which performed
It is not good to use the current method to achieve cross-cutting points. It will bring some problems, we can roughly divide these problems into two categories.
Code confusing: Modules in the software system may take care of several aspects. For example, developers often consider issues such as business logic, performance, synchronization, logs, and security, and take into account the needs of all aspects, resulting in the implementation elements of the corresponding attention, causing code confusion. Code Dispersion: Due to cross-cutting points, it is involved in multiple modules, and the relevant implementation has to be all over these modules. If in a system that uses the database, performance issues affect all modules that access the database. This leads to code dispersion at all areas
result
Confusion and dispersed code will affect the design and development of the system in multiple aspects:
The ability to readability is poor: the simultaneous implementation of the achievements of different attention points, making the corresponding relationship between the focus and its implementation are not obvious.
Low output: Simultaneous implementation of several concerns to transfer developers from primary transfer to peripheral attention, resulting in low capacity.
Low-code reusability: Due to this case, a module implements multiple attention points, others need to use the module immediately to further reduce capacity immediately.
The code quality is poor: the chaotic code covers the problem hidden in the code. Moreover, due to the simultaneous handling of multiple attention points, special attention should not be concerned about the attention
It is difficult to expand: narrow perspectives and limited resources always produce only the design of current concerns. New demand leads to new implementation. Since the implementation is not modular, it is to implement multiple modules. In order to modify the subsystem in order to make data, it is necessary to ensure that these modifications will not bring BUG.
Current solution
Since most systems include cross-cutting points, natural has formed some technologies to modularize the implementation of cross-cutting points, including: mixing, design patterns and solutions for specific problem domains
Using mixed class, you can postpone the ultimate implementation of your attention. The basic class contains an instance of mixing classes, allowing the other part of the system to set this instance, an example, to implement the business logic class contains a mixed Logger, and the other parts of the system can set this Logger to get the appropriate log type. For example, Logger may be set to use the file system or a message middleware. In this way, although the specific implementation of the log is postponed, the basic class is also included in all write logs to the point-in-time log operation and control log information. Code.
Behavior design patterns, such as Visitor and Template mode, also allow you to postpone specific implementation. But just like mixing, the control - calling Visitor or Template logic - still left for basic classes
Solution to specific problem domains, such as frameworks and application servers, allowing developers to handle certain cross-cutting points in a more modular manner. For example, EJB (Enterprise Javabean, Enterprise Javabean) architecture, can handle the perspective of the persistence of safe, system management, performance, and container-managed persistence. BEAN developers only need to care about business logic, and deployers only need to deploy issues, such as beans and database mappings. But in most cases, developers still have to understand the storage structure. In this way, you use an XML-based mapping relationship descriptor to achieve cross-cutting points related to data persistence.
Solution to specific issues provides a special mechanism to solve specific problems. Its disadvantage is that the developers must re-learn for each such solutions, and because this approach is related to a specific problem domain, which belongs to a specific Crosshasses outside the problem require special treatment
Down difficult situation of designers
A good system designer will not only consider current needs, but also considering the need to be able to avoid patch everywhere. This will have a problem, and it is very difficult to predict the future. If you leak over the need for cross-cutting points in the future, you will need to modify or even re-implement a number of parts; from another angle It is said that it is too concerned that there is not necessarily designed to lead to overdesigned, difficult to understand, bloated systems. Therefore, the system designer is in such a two difficult situation: How to design calculate? It should be reasonable to design is not too much? For example, is the designer should include the log mechanism that is not needed in the system? If so, where is the point you should write a log? What information should you record? Similar examples have the optimization of performance, we rarely know the bottlenecks in advance. Common methods are to create systems, profile, and then refurbish the system to improve performance, in this way, in this way, many parts of the system can be modified in the profiling, in addition, as time passes, due to changes in use, it may also produce new The task of bottlenecks and class library designers is more difficult because he is hard to enlighten all the ways of using the class library.
All in all, the designer is hard to take into account all the attention points that the system may need to process. Even under the premise of knowing the demand, some details that are required to establish a system may not be available. The overall design is facing two difficulties in designing insufficient design / over-design.
AOP foundation
The discussion of the current discussion is good for modular cross-cutting points. Researchers have tried a variety of ways to achieve this task, which has a common topic: separation attention. AOP is one of these methods, and its purpose is to clearly separate the concerns to solve the problems mentioned above.
AOP, from its inherent, allow you to achieve independent attention in a loosely coupled manner, then combine these implementations to establish the final system. It is built using the system it established to use loosely coupled and modular realization. In contrast, the system established with OOP is achieved by a general concern of a loosely coupled modular implementation. In AOP end, these modular units are called, while in OOP, the implementation unit of these general interest points is called classes.
AOP includes three clear development steps:
Aspects Decomposition: Decompose demand extracts cross-cutting points and general concerns. In this step, you separate the core module-level focus and system levels. For example, the credit card mentioned earlier, you can decompose three attention points: core credit card processing, logs, and verification.
Confusion point implementation: Independent implementation of these concerns, also use the above credit card example, you want to implement the credit card processing unit, the log unit, and the verification unit.
SCIENTIARUM NATURALIUM UNIVERSITATIS. In this step, aspect integrators specify the rules of the reorganization by creating a module unit. Recombination process - also called woven or combined - use this information to build the final system, also take the one example of a credit card, you can specify (the language provided with a AOP) Each operation start and end Records are required, and each operation must be verified before involving business logic.
Figure 3. Steps for AOP development
The different key to the AOP and OOP is that it handles the way to pay attention to the point. In the AOP, you don't know if the implementation of each focus point will 'attention' it, if the credit card processing module does not know other attention points Implementation is doing logs and verification operations for it. It shows a powerful development model that is converted from OOP.
Note: An AOP implementation can use other programming models as its basis, so that it is unpacked to retain its basic model. For example, AOP can select OOP as its basic model, thereby taking OOP to the benefits of processing general attention. With such an implementation, independent general concerns can use OOP technology. This is like the process-type language is the basis of many OOP languages. Exemplary
Volume - a processor - assembles a point of interest (this process is called woven). That is to say, mixing different execution logical sections in accordance with the rules provided to it.
To illustrate the code, let us return to the credit card processing, for the sake of simplicity, we only consider two operations: deposit and removal, and we have assumed that there is already a suitable Logger.
Let's take a look at the following credit card module:
public class CreditCardProcessor {public void debit (CreditCard card, Currency amount) throws InvalidCardException, NotEnoughAmountException, CardExpiredException {// fetch logic} public void credit (CreditCard card, Currency amount) throws InvalidCardException {// stored logic
}
Below is a log interface
Public interface logger {public void log (string message);
The combination of desired needs need to be woven into rules, here is expressed in natural language (the program version of these woven rules will be provided later):
1. Record the beginning of each public operation
2. Record the end of each public operation
3. Record all public methods thrown
The web will use these woven rules and focus points to generate code with the same effect as the following code:
public class CreditCardProcessorWithLogging {Logger _logger; public void debit (CreditCard card, Money amount) throws InvalidCardException, NotEnoughAmountException, CardExpiredException {_logger.log ( "Starting CreditCardProcessor.credit (CreditCard, Money)" "Card:" card "Amount: " Amount); // Removed Logic _Logger.log (" Completion CreditcardProcessor.credit (CreditCard, Money) " " Card: " Card " Amount: " Amount);} public void Credit (CreditCard Card, Money Amount Throws invalidcardException {system.out.println ("debits"); _logger.log ("Starting CreditcardProcessor.debit (Creditcard, Money)" "Card:" Card "Amount:" Amount); // Deposit Logic_Logger.log ("Completion CreditcardProcessor.credit (CreditCard, Money)" "Card:" Card "Amount:" Amount);}} AOP language profiling
Just like other programming models, the implementation of AOP has two parts: language specification and implementation. Language specification describes the basic unit and syntax of the language. Language Implementation follows the language specification to verify the correctness of the code and convert the code to the executable of the target machine. This section, I explain the AOP component.
AOP language specification
From an abstract angle, an AOP language must explain the following two aspects:
Implementation: Map each requirement to code, then the compiler translates it into an executable code. Since the implementation of the focus is in the form of a designated process, you can use traditional languages such as C, C , Java, etc.
Weaving rules specification: How to combine independent achievements to form the final system? For this purpose, it is necessary to establish a language to specify a different implementation unit to form the final system, which specifies the language of the woven rule, can be an extension of the language, or a completely different language.
AOP language implementation
AOP compiler performs two steps:
1. Assemble the attention point.
2. Transfer assembly results into executable code
AOP implementation can be woven in a variety of ways, including source code to source conversion. It preproces the source code for each aspect to produce the woven source, and then give the woven source code to the compiler of the base language to generate the final executable code. For example, using this approach, a Java-based AOP implementation can first convert different aspects into Java source code, and then let the Java compiler turn it into one by section code. It is also possible to perform woven in the bytecode level; after all, the bytecode itself is also a source code. In addition, the following execution system -Java virtual machine can also be awareness, Java-based AOP implementation If you use this method, the virtual machine can load the woven rules first, and then put the class that later loaded This rule is applied, that is, it can perform Just-in-Time woven. The benefits of AOP
AOP helps us solve the problems caused by the code chaos and code disperses mentioned above, and it has some other benefits:
Modular cross-cutting points: AOP is used to handle each payment point with minimal coupling, so that even cross cutting points are also modular. Such implementation is generated, and the redundancy of its code is small. Modular implementation also makes the system easy to understand and maintain
The system is easy to expand: Since the aspect module does not know the cross-cut point, it is easy to add new features by establishing a new aspect, and when you join a new module to the system, existing automatic cross cuts. , Make the system easy to expand
The delayed binding of the design decision: Remember the two difficulties of the designer? Using AOP, designers can postpone the decision for future demand, as it can make this demand as an independent implementation.
Better code reuse: Since the AOP implements each aspect as a separate module, the module is loosely coupled, for example, you can use another independent log writer (replace the current) to log the log Write a database to meet different log write requirements. In general, the realization of loose coupling means better code reuse, and AOP is better than OOP to make system loose coupling.
AspectJ: A Java AOP implementation
Aspectj is a free AOP implementation, a use of Xerox Parc, developing Java, is a multi-function-oriented Java extension. It uses Java as a single payment point implementation language and expands Java to specify the woven rules. These rules are based on the PointCuts, Join Points, Notifications, and aspects (aspect). The joint point is to define the point between the program execution process, the entry point is constructed by the language configuration used to specify the joint point, and notify the code to define the code to execute on the cut point, and aspect is a combination of these base elements.
In addition, AspectJ allows for a variety of ways to establish new aspects, you can introduce new data members and methods, or declare a new class to inherit and implement additional classes or interfaces.
AspectJ's Wooler - The Compiler of AspectJ - is responsible for combining different aspects, because the final system established by the AspectJ compiler is a pure Java bytecode, which can run on any virtual machine that meets Java standards . Moreover, AspectJ provides some tools such as debuggers and Java IDE integration, etc., I will explain in detail in this series.
Below is an Aspectj implementation I woven in the log in the log in the natural language, because I will introduce Aspectj in the second part, so I don't have to worry if you can't understand it. The key is that you should notice that the credit card processing process itself does not know the log.
public aspect LogCreditCardProcessorOperations {Logger logger = new StdoutLogger (); pointcut publicOperation (): execution (public * CreditCardProcessor * (..).); pointcut publicOperationCardAmountArgs (CreditCard card, Money amount): publicOperation () && args (card, amount) ; before (CreditCard card, Money amount): publicOperationCardAmountArgs (card, amount) {logOperation (. "Starting", thisjoin point.getSignature () toString (), card, amount);} after (CreditCard card, Money amount) returning: publicOperationCardAmountArgs (card, amount) {logOperation ( "Completing", thisjoin point.getSignature () toString (), card, amount.);} after (CreditCard card, Money amount) throwing (Exception e): publicOperationCardAmountArgs (card, amount) {LogOperation ("Exception" E, thisjoin Point.getsignature (). Tostring (), Card, Amount);} private void logope Ration (String Status, String Operation, Creditcard Card, Money Amount) {Logger.log (Status "" Operation "Card:" Card "Amount:" Amount);}} I need AOP?
Is AOP only solve the shortcomings of design? In AOP, each of the interest points do not know if there are other attention points to pay attention to it, this is the main difference between AOP and OOP, in AOP, the combination of flow is from cross-cutting points to the main concern point, and OOP is the opposite, but OOP can coexist with AOP. For example, you can use a combination of mixed classes that can be implemented in AOP, or you can use OOP implementation, which depends on your acceptance of AOP. In both cases, it is not necessary to know that it is used in the class in both cases. For example, you can use a log writer interface as a class of mixed classes or as a log. Thus, from OOP to AOP gradually.
Learn about AOP
In this article, you have seen problems with cross-cutting relationships, the current solutions of these issues, and the disadvantages of these methods. You also saw how the AOP overcomes these shortcomings. AOP programming method is an implementation of modular cross-cutting points, providing a better and faster software development method. If you involve multiple cross-cut points in your system, you can consider further understanding AOP, its implementation, its benefits. AOP is likely to be a programmed wayside milestone. Please continue to pay attention to the second, third part of this series.