Separating the business logic in your application from the generic services that support it

Source: Internet
Author: User

AOP (aspect-oriented programming, aspect-oriented programming) can be said to complement and improve OOP (object-oriented programing, object-oriented programming). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to create an object hierarchy that simulates a collection of public behavior. When we need to introduce public behavior to scattered objects, oop seems powerless. In other words, OOP allows you to define relationships from top to bottom, but it is not appropriate to define left-to-right relationships. such as logging capabilities. Log code is often spread horizontally across all object hierarchies, and has nothing to do with the core functionality of the objects it spreads to. This is true for other types of code, such as security, exception handling, and transparent persistence. This irrelevant code scattered around is called crosscutting (cross-cutting) code, and in OOP design, it leads to a lot of duplication of code, rather than the reuse of individual modules.

AOP, on the contrary, uses a technique called "crosscutting" that splits the encapsulated object interior and encapsulates public behavior that affects multiple classes into a reusable module, called "Aspect", which is the facet. The so-called "aspect", in a nutshell, is to encapsulate the logic or responsibility that is not related to the business, but for the common invocation of the business module, to reduce the duplication of code in the system, to reduce the coupling between modules, and to facilitate future operability and maintainability. AOP represents a horizontal relationship, if the "object" is a hollow cylinder, which encapsulates the properties and behavior of the object, then the aspect-oriented programming approach is like a razor that cuts through the hollow cylinders to get inside the message. The cut-off aspect is the so-called "facet". Then it hands the cut-off slices with a clever capture of the heavens, leaving no traces.

Using "crosscutting" techniques, AOP divides software systems into two parts: core concerns and crosscutting concerns. The main process of business process is the core concern, and the part that has little relation is the crosscutting concern. One feature of crosscutting concerns is that they often occur in many of the core concerns and are essentially similar everywhere. such as permission authentication, logging, transaction processing. The role of AOP is to separate the various concerns in the system, separating the core concerns from the crosscutting concerns. As Avanade's senior program architect Adam Magee says, the core idea of AOP is "separating the business logic in the application from the generic services that support it." ”

The implementation of AOP technology, mainly divided into two categories: first, the use of dynamic Agent technology, the use of interception of messages to decorate the message to replace the original object behavior, the second is the use of static weaving, the introduction of a specific syntax to create "aspects", so that the compiler can be woven into the relevant "aspects" The code. However, the technical characteristics of AOP are the same, namely:

1. Join point: A precise point of execution in the execution of a program, such as a method in a class. It is an abstract concept, and when implementing AOP, there is no need to define a join point.
2. Point Cut (pointcut): essentially a structure that captures the connection point. In AOP, you can define a point cut to capture calls to related methods.
3. Advice (notice): Is the execution code of point cut, is the concrete logic of executing "aspect".
4, Aspect (aspect): Point cut and advice together is aspect, which resembles a class defined in OOP, but it represents more of the horizontal relationship between objects.
5, introduce (introduced): to introduce additional methods or properties for the object, so as to achieve the purpose of modifying the object structure. Some AOP tools refer to them as mixin.

The technical features described above form the basic AOP technology, and most AOP tools implement these technologies. They can also be the basic terminology for studying AOP technology.

2.2.2 Crosscutting Technology

"Crosscutting" is the proper term for AOP. It is a relatively simple design and programming technique that contains powerful power, especially when it comes to building loosely coupled, scalable enterprise systems. Crosscutting techniques enable AOP to move through a given set of responsibilities (such as logging and performance optimization) in a specific programming model.

What happens to software development without using crosscutting techniques? In traditional programs, because the implementation of crosscutting behavior is decentralized, it is difficult for developers to implement or change these behaviors logically. For example, the code used for logging is intertwined with code that is primarily used for other duties. Depending on the complexity of the problem being solved and the scope of the difference, the resulting confusion can be large and small. Changing the logging policy for an application can involve hundreds of edits-even if it works, which is a daunting task.

In AOP, we refer to the behavior of these common logic, which is entangled with the core logic of other modules, as "crosscutting concerns (crosscutting Concern)" because it spans the typical line of duty in a given programming model.

2.2.2.1 crosscutting Concerns

A point of concern (concern) is a specific purpose, a region of interest to us, a logical act we need. From a technical point of view, a typical software system contains some core concerns and system-level concerns. For example, the core focus of a credit card processing system is loan/deposit processing, while system-level concerns are log, transaction integrity, authorization, security, and performance issues, and many of the concerns-crosscutting concerns (crosscutting concerns)-occur in multiple modules. With existing programming methods, crosscutting concerns traverse multiple modules, resulting in a system that is difficult to design, understand, implement, and evolve. AOP provides a better separation of system concerns than the above approach, providing a modular crosscutting focus.

For example, a complex system, which is implemented by a number of focus points, such as business logic, performance, data storage, logging and scheduling information, authorization, security, threading, error checking, etc., as well as the focus of the development process, such as easy to understand, easier to maintain, easy to trace, easy to expand, etc. Figure 2.1 illustrates a system that consists of a group of concerns implemented by different modules.


Figure 2.1 The module as a batch of concerns to achieve

By identifying the requirements and implementation of the system, we can divide these concerns in the module into core concerns and crosscutting concerns. For core concerns, the modules that implement these concerns are usually independent of each other, and they complete the business logic required by the system, which is related to the specific business requirements. For the logs, security, persistence and other concerns, they are the business logic module common needs, these logic is distributed in the core focus of the various places. In AOP, such modules are referred to as crosscutting concerns. The key to the application of AOP is to realize the recognition of the focus point.

If the entire module is likened to a cylinder, then the focus recognition process can be described by the Prism law, through the prism beam (refers to the demand), irradiation to the cylinder everywhere, to obtain different color of the beam, and finally identify the different concerns. 2.2 is shown below:


Fig. 2.2 Focus Recognition: Prism law

In the identified concerns, business logic is a core concern, and it calls to cross-cutting concerns such as security,logging,persistence.

public class Businesslogic
{
public void Someoperation ()
{
Verify security; securtity focus;
Record log before execution; logging attention point;

DoSomething ();

Save the data after the logical operation; persistence focus;
Execution end logging; logging focus;
}
}

The purpose of AOP is to separate crosscutting concerns such as logging from the Businesslogic class. Using AOP technology, the relevant crosscutting concerns can be encapsulated to form a separate "aspect". This guarantees the reuse of crosscutting concerns. Because the Businesslogic class no longer contains the logical code for crosscutting concerns, to achieve the purpose of invoking crosscutting concerns, you can take advantage of crosscutting techniques to intercept messages for related methods in the Businesslogic class, such as the Someoperation () method, and then add these " Aspect "is woven into this method. Example 2.3:


Figure 2.3 Weaving cross-cutting concerns into core focus points

Through the use of AOP technology, the entire system has changed the way the design. At the beginning of analyzing the system requirements, we use the idea of AOP to isolate the core concerns and cross-cutting concern points. After implementing common logic for crosscutting concerns such as logging, transaction management, and permission control, developers can focus on core concerns and devote their energies to solving business logic. At the same time, these packaged crosscutting concerns provide the ability to maximize the reuse of various parts of the business logic, without the need for special coding by developers or the impact of specific business functions by modifying the functionality of crosscutting concerns.

In order to build loosely coupled, extensible enterprise systems, the crosscutting techniques applied to AOP are generally divided into two types: dynamic crosscutting and Static crosscutting.

2.2.2.2 Dynamic crosscutting

Dynamic crosscutting is the process of creating behaviors in one aspect through pointcuts and connection points that can be applied horizontally to existing objects at execution time. Dynamic crosscutting is typically used to help add logging or authentication to various methods in the object hierarchy. In many application scenarios, dynamic crosscutting techniques represent AOP in essence.

The core of dynamic crosscutting technology consists of join Point (Junction), Points cut (pointcut), advice (notification) and aspect (aspect). In the preceding sections, I have outlined the meanings that these terms represent respectively. Next, I'll take a concrete example to further illustrate the significance of their implementation in AOP dynamic transversal.

Consider an e-commerce system, need to add to the order, delete and other management operations. There is no doubt that in real-world scenarios, these behaviors should be combined with rights management, and only authorized users can implement them. Using the traditional design method, the pseudo code is as follows:
public class OrderManager
{
Private ArrayList m_orders;
Public OrderManager ()
{
M_orders = new ArrayList ();
}
public void AddOrder (order order)
{
if (permissions. Verify (Permission.admin))
{

M_orders.add (order);
}
}

public void Removeorder (order order)
{
if (permissions. Verify (Permission.admin))
{
M_orders.remove (order);
}
}
}

Similarly, in this e-commerce system, commodities need to be managed, with the same authorization mechanism:
public class Productmanager
{
Private ArrayList m_products;
Public Productmanager ()
{
m_products = new ArrayList ();
}
public void Addproduct (product product)
{
if (permissions. Verify (Permission.admin))
{
M_products.add (product);
}
}
public void Removeproduct (product product)
{
if (permissions. Verify (Permission.admin))
{
M_products.remove (product);
}
}
}

Thus, throughout the e-commerce system, the core business includes order management and commodity management, all of which require the same rights management, as shown in 2.4:


Figure 2.4 Authorization validation for e-commerce system

Without a doubt, using AOP technology, we can isolate the core concerns and crosscutting concerns of the system, and intercept the internal message of the business management behavior from the horizontal angle, in order to achieve the purpose of weaving the rights management logic. When a method such as AddOrder () is executed, the system verifies the user's permissions and invokes the crosscutting concern logic so that the method is an AOP join point. For an e-commerce system, each method that requires permission validation is a separate join point. Because permission validation will be performed before each method executes, you only need to define a point cut for this series of join point. When the system executes to the join point, it looks for the corresponding point cut according to the definition, and then executes the logic that the crosscutting concern needs to implement, namely advice. The point cut and advice are combined into a rights management aspect.


Figure 2.5 The technology implementation of AOP dynamic crosscutting

Since aspect is an encapsulated object, we can define such a aspect:
Private static aspect authorizationaspect{...}

Then you define point cut in this aspect, and in point cut, you define a method that needs to intercept the context message, for example:
Private Pointcut authorizationexecution ():
Execution (public void Ordermanager.addorder (Order)) | |
Execution (public void Ordermanager.deleteorder (Order)) | |
Execution (public void productmanager.addproduct (Product)) | |
Execution (public void productmanager.deleteproduct (Product));

Because permission validation is done before the order management method executes, the permission check is defined in before advice:
Before (): Authorizationexecution ()
{
if! (Permissions. Verify (Permission.admin))
{
throw new Unauthorizedexception ();
}
}

By defining such a complete aspect, when the system calls the relevant method of OrderManager or Productmanager, the point cut is triggered, and then the corresponding advice logic is invoked. Since then, the OrderManager and Productmanager modules have completely lifted the dependency relationship with the Rights Management module, while eliminating the duplication of code that is unavoidable in traditional design for permission judgments. This is advantageous for building a loosely coupled, extensible system software.

2.2.2.3 Static crosscutting

The difference between static and dynamic crosscutting is that it does not modify the execution behavior of a given object. Instead, it allows you to modify the structure of an object by introducing additional method fields and properties. In addition, static crosscutting can attach extensions and implementations to the basic structure of an object. In an AOP implementation, static crosscutting is often referred to as introduce or mixin.

Static crosscutting is a relatively small concern in AOP technology. In fact, the potential of this technology is enormous. Using static crosscutting, architects and designers can effectively build models of complex systems with a truly object-oriented approach. Static crosscutting allows you to insert public behavior that spans the entire system without creating a deep hierarchy, in a way that is inherently more elegant and more realistic than the actual structure. In particular, when developing application systems, if you need to introduce third-party products and API libraries without modifying the original code, static crosscutting techniques will play a huge role.

For example, a mail messaging system has been implemented, with class mail completing the ability to send and receive messages. However, after the delivery of the product, it was found that the system was defective, and the e-mail address verification function was not implemented when sending and receiving mail. Now, the third-party product has provided the interface for the validation function ivalidatable:
public interface Ivalidatable
{
BOOL Validateaddress ();
}

We can use the adapter pattern in design mode to complete calls to third-party product APIs. We can define a new class Mailadapter, which implements the Ivalidatable interface and inherits the Mail class:
public class Mailadapter:mail,ivalidatable
{
public bool Validateaddress ()
{
if (this.gettoaddress () = null)
{
return true;
}
Else
{
return false;
}
}
}

By introducing the Mailadapter class, the original mail object completes the operation, will be all replaced by the Mailadapter object. However, this implementation can solve the problem of introducing a new interface, but it is not possible to compile the code like the following:
Mail mail = new mail ();
Ivalidatable validate = ((ivalidatable) mail). Validateaddress ();

The first line of code must be modified as follows:
Mail mail = new Mailadapter ();

Using the static crosscutting technique of AOP, the Ivalidatable interface can be woven into the original mail class, which is a very image introduce function, and its implementation is still done in aspect:
Import com.acme.validate.Validatable;

Public Aspect Mailvalidateaspect
{
Declare Parents:mail implements Ivalidatable;

public boolean mail.validateaddress ()
{
if (this.gettoaddress () = null)
{
return true;
}
Else
{
return false;
}
}
}

Static crosscutting methods do not introduce new classes similar to Mailadapter, but through the mailvalidateaspect aspects of the definition, using crosscutting techniques to introduce a new method for the Mail class validateaddress (), Thus, the extension of mail is realized. So the code below is completely doable.
Mail mail = new mail ();
Ivalidatable validate = ((ivalidatable) mail). Validateaddress ();

Advantages of 2.3 AOP Technology

The advantages of AOP technology are obvious. In the object-oriented world, a variety of methods and design principles are proposed to ensure the reusability and expansibility of the system, in order to establish a loosely-coupled, easy-to-extend software system. For example, the "design pattern" proposed by GOF provides us with a model and guideline for our design. Design patterns are designed to be flexible, extensible, reusable libraries, components, and architecture of the entire system by maximizing the use of object-oriented features, such as the use of inheritance, polymorphism, separation of responsibilities, inversion of dependencies, and abstraction-oriented interfaces. In the process of design, the behavior of the object, the exposed interface, the relationship between the objects and the morphology of the objects in different levels are manifested through various modes. However, in view of the particularity of object encapsulation, the antennae of "design pattern" are always in the way of interface and abstraction, while there is nothing to do with the interior of objects.

With "crosscutting" technology, AOP technology can go deep into the object, and intercept the messages passed between the methods used by me. By completely isolating the core concerns from the crosscutting concerns, we are able to program the "aspect" independently. It allows developers to dynamically modify the static OO model and construct a system that can grow to meet the new needs, just as real-world objects change themselves throughout their life cycles, and applications can have new capabilities in development.

The advantages of applying AOP technology when designing software systems are:

(i) When defining all the requirements of an application for a service, such as a log. By identifying concerns, the service can be better defined, better coded, and more functional. This approach can also deal with problems that arise when code involves multiple functions, such as changing a feature that might affect other functions, and in AOP call this Trouble "Tangled (tangling)".

(ii) The analysis of discrete aspects using AOP techniques will help to designate an expert who is proficient in the work for the development team. The best candidates for this work will be able to use their relevant skills and experience effectively.

(iii) sustainability. In standard object-oriented project development, different developers typically write the same code for a service, such as logging. They then process the logs separately in their own implementation to meet the needs of different individual objects. By creating a separate code snippet, AOP provides a durable and simple solution to this problem, which emphasizes reusability and maintainability of future functionality: there is no need to rewrite the log code over and over throughout the application, and AOP makes it possible to write only the log aspect (logging aspect) is possible and can provide new functionality for the entire application on top of it.

All in all, the benefits of AOP technology greatly reduce the amount of code that needs to be written, saving time and controlling development costs. It also allows developers to focus on the core business logic of the system. In addition, it facilitates the creation of loosely coupled, reusable and scalable large software systems.

Reference connection: http://wayfarer.cnblogs.com/articles/241012.html

Http://www.cnblogs.com/zhenyulu/zhenyulu/articles/234074.html

Http://www.cnblogs.com/zhugenqiang/archive/2008/07/27/1252761.html

Separating the business logic in your application from the generic services that support it (GO)

Related Article

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.