The business logic layer design of five PetShop
The Business Logic layer (Business Logic Layer) is undoubtedly the part of the system architecture that embodies the core value. Its focus is mainly on the development of business rules, the implementation of business processes and other business requirements related to the system design, that is, it is related to the domain of the system to deal with the logic, many times, we also call the business logic layer as the domain layer. For example, Martin Fowler, in the book Patterns of Enterprise Application architecture, divides the entire architecture into three main layers: the presentation layer, the domain layer, and the data source layer. Eric Evans, the pioneer of domain-driven design, makes a more detailed division of the business Logic layer, divided into application and domain layers, and further separates domain logic from domain logic solutions by layering.
The position of the business logic layer in the architecture is critical, it is in the middle of the data access layer and the presentation layer, and it plays the role of the connecting link in the data exchange. Because the layer is a weakly coupled structure, the dependency between the layers is downward, the bottom layer is "ignorant" to the upper layer, and changing the top design has no effect on the underlying level of the call. If you follow the idea of interface-oriented design in layered design, this downward dependency should also be a weak dependency. Thus, without changing the definition of the interface, the ideal layered architecture should be a "drawer" architecture that supports the removable, replaceable type. Because of this, the design of the business logic layer is particularly critical to support an extensible architecture, because it plays two different roles. It is the caller for the data access layer, but it is the caller for the presentation layer. Dependence and dependency are entangled in the business logic layer, how to realize the decoupling of dependency is the task left to the designer except to realize the business logic.
5.1 Cooperation with field experts
The biggest obstacle of designing business logic layer lies not in technology, but in the analysis and understanding of domain business. It is hard to imagine that an architect who is unfamiliar with the business rules and processes in the field can design a system architecture that meets the needs of the customer. It is almost possible to conclude that the design process of the business logic layer must involve the domain experts. I have been involved in the development of the project, covering the field of electricity, semiconductors, automobiles and many other industries, if the lack of experts in these areas, software architecture design, especially the business logic layer design is impossible to talk about. The only exception to this conclusion is that architects are also experts in the field. However, it is very difficult to find such outstanding talents because the so-called "thousand Army is easy to get, one will be difficult to ask".
The role of field experts in the team is often referred to as business Consultor (business consultant), responsible for providing consulting on the domain business, working with the architect on the design of the architecture and database, composing requirements documents and design use cases (or user stories, Story). If you are in the testing phase, you should also include writing test cases. Ideally, the domain experts should be involved in the development of the entire project, not just the requirements phase.
Field experts can be specialized consultants who have a deeper attainments in the field, or customers who serve as demand providers. In extreme Programming (Extreme programming), customers are introduced to the entire development team as domain experts. It emphasizes the field customer principle. Onsite customers need to participate in all stages of project development, such as planning games, developing iterations, and coding tests. As domain experts and designers and developers form a team, throughout the development process, you can avoid the need to understand the error occurred. Even if the development of the project is not in conformity with the actual requirements, it can be corrected early in the project so as to avoid unnecessary postponement of the project and strengthen the control over the process and cost of the project. As Steve McConnell in the early stages of building an activity: the time to find the error is as close as possible to the time when the error was introduced. The longer the bug in the system lurks, the more expensive it will cost. If you can cooperate fully with the field experts in the project development, we can avoid such a vicious chain reaction with maximum effect.
The traditional software development model also attaches importance to the cooperation with domain experts, but this kind of cooperation mainly concentrates on the requirement analysis stage. The waterfall model, for example, emphasizes early planning and demand research. However, this proactive planning approach is very demanding for architects and demand investigators, emphasizing the accuracy of the requirements document, once the analysis is biased, or if the requirements change, and as the project develops into the design phase, it lacks the mechanism to communicate and collaborate with the domain experts, Developers can not estimate these errors and errors, so it is difficult to make timely corrections. Once these problems spread like a cancer in the system and become exposed to the developers, they have become an insurmountable mountain. We need to consume more human and material resources to be able to correct these errors, which leads to an increase in the number of development costs, and even lead to project delays. Of course, there is a good choice, is to abandon the whole project. Such examples abound, in fact, the reason for the "Waterloo" of project development is mostly due to problems in business logic analysis.
The iterative model has greatly improved compared with the waterfall model, because it allows for changes and optimizes system requirements, the entire iterative process is actually a collaborative process with domain experts, by demonstrating the system functionality generated by the iteration to the customer, to get feedback in time, and to solve the problems that arise in an iterative demo, Ensure that the system evolves in a way that meets customer needs. Thus, an iterative model can often solve the problem of insufficient early planning, which allows the redesign, recoding, and testing of changes in requirements when a defect is found.
Regardless of the development model, cooperation with field experts will be the key to success or failure of the project. This is based on the universal truth of a software development that there is no constant demand in the world. A classic quote is: "There is no constant demand, the world's software has been changed more than 3 times, the only one changed only two software owners have died, die in the road to modify demand." "A word to do the software development of cruelty and hardship!"
So how should we strengthen cooperation with experts in the field? Based on their experience with the IBM SanFrancisco Project, James Carey and Brent Carlson the innocent questions model, meaning "improving the quality of communication between field experts and technical experts". In a project team, if we don't have a candidate who can be both a chief architect and a domain expert, it is particularly important to strengthen the collaboration of field experts and technical experts. After all, as a field expert, you may not be familiar with software design methodologies or the ability to target object-oriented development and architectural design, and most technical experts are likely to have only a smattering of business areas involved in the project. If field experts and technical experts fail to communicate effectively, the future of the entire project is at stake.
The solutions proposed in the Innocent questions model include:
(1) Selection of people who can live in harmony with the formation of development team;
(2) clearly define roles and competencies;
(3) clearly define the desired interaction points;
(4) Keep the team close;
(5) Hire good people.
In fact, this has risen from a technical perspective to a management level for the team. Just like basketball, even if your team brings together five of the world's top and most gifted players, it is still very difficult to win a match if you are fighting for each other. Teamwork and responsibility are clearly the guarantee of success, software development is the same.
The basis for working with field experts is to ensure that at least one field expert is retained in the development team. He can be a client of the system, a consultant to a third party company, and ideally an expert hired by his own company. If there is a lack of such a person in the project, then my advice is to hire him if you don't want to see the project suffer from the Siberian cold.
Identify the role tasks and responsibilities of the domain experts. It is important for everyone on the team to make clear what role the field experts play in the entire team and what their responsibilities are. A qualified field expert must have a deep understanding of the business area, and he should be a person who overlooks the overall needs of the system. In the process of project development, he will be responsible for the development of business rules and procedures, responsible for communication with customers, demand research and discussion, and the designer to participate in the design of the system architecture. A document is a work that a domain expert must participate in, whether it be a requirement document or a design document, and the preparation of a use case, a domain expert or an opinion, or as the author of a composition, at least he should be an important member of the Review Committee.
Standardize terminology and technical terminology in the business area. Field experts and technologists must communicate and communicate in a semantic environment that guarantees no two meanings. If there is a divergence of understanding, we must resolve it in time to establish terminology standards through discussion. It is hard to imagine that two of people with language difficulties can cooperate with each other happily, and the solution is to join a translator. To build a semantic bridge between field experts and technical experts, so that they can understand each other and identify with each other. Another option would be to conduct training activities within the team. Especially for developers, more or less understanding of some business areas of knowledge, for the development of the project has a great help. In my field of semiconductor project development, the team specifically invited the semiconductor industry experts on the production process of the business logic of a full range of introduction and training. The so-called "Maito", although we spend the training time, but for the master of the business rules and procedures of the developers, but can improve the progress of the project development, the overall savings in development costs.
To strengthen communication with customers. Customers can also be a team of domain experts, the extreme programming of the field customer principle is the best example. But the reality is not so perfect, in the inability to ask customers to become a fixed member of the development team, hire or arrange a specialized field experts, strengthen communication with customers, it is particularly important. The project can obtain the customer's prompt feedback through the domain expert. It is possible to reduce the demand error to the greatest extent by understanding the changing requirements through domain experts.
5.2 Mode application of business logic layer
Martin Fowler the architectural pattern of the domain layer (the Business logic layer) in the enterprise Application architecture model, and he divides the business logic design into three main modes: Transaction Script, Domain model, and table Module.
Transaction Script Mode regards business logic as a process and is a typical process-oriented development model. Applying the transaction script pattern allows you to access the database directly using SQL statements without requiring a data access layer. In order to effectively manage SQL statements, you can place the behavior related to database access in a specialized gateway class. The application of Transaction script mode does not require too much object-oriented knowledge, and the simple and direct feature is the whole value of the model. Therefore, in many business logic relatively simple project, the application transaction script pattern is more.
The Domain model model is the embodiment of the typical object-oriented design idea. It takes full account of the complexity and variability of the business logic, this paper introduces the idea of design pattern, such as strategy mode, and realizes the extensibility of the pattern by establishing the domain object and the abstract interface, and uses the object-oriented thought and the inherent characteristics, such as inheritance, encapsulation and polymorphism, to deal with the complex and changeable business logic. The only thing that restricts the application of this pattern is the mapping of objects to relational databases. We can either introduce ORM tools or use the data mapper pattern to map relationships to objects.
Similar to the domain model model is the table module mode, which also has the idea of object-oriented design, the only difference is that the object it obtains is not a simple domain object, but a DataSet object. If you create a simple mapping relationship between a relational datasheet and an object, the domain model model is to create a domain object for each record in the datasheet, and the table module pattern is to treat the entire datasheet as a complete object. Although the use of DataSet objects will lose the basic object-oriented features, it has a unique advantage in providing data source support for the presentation layer. Especially in. NET platform, ADO. NET and Web controls provide fertile soil for the table module pattern to grow.
Business Logic Layer design of 5.3 petshop
PetShop the domain model model in the business Logic layer design, which is inseparable from the data access layer's support to the data object. Because PetShop does not carry on the business logic of the pet online store deeply, also omitted many complex details business logic, therefore in Domain model model application is not obvious. It is most typical to handle the order domain object by introducing the strategy pattern to complete the encapsulation of the behavior of the inserts. In this regard, I have a detailed description of the 27th chapter, no longer repeat here.
This should be the most core business logic layer in the system architecture design, which makes the design of petshop in this layer somewhat lackluster because of simplifying the business process. Although in the business logic layer, the related domain objects are defined for the business, but these domain objects simply encapsulate the data objects in the data access layer only for the purpose of separating the tiers to support the expansion of the various databases while excluding the SQL statements from the business logic layer. Avoids the spread of SQL statements.
The best embodiment of petshop business logic in addition to the management of orders, but also includes shopping cart (Shopping cart) and wish list management. In the PetShop BLL module, the cart class is defined to be responsible for the relevant business logic, defined as follows:
[Serializable]
public class Cart
{
private Dictionary cartitems = new Dictionary ();
Public decimal Total
{
get
{
decimal total = 0;
foreach (CartItemInfo item in cartitems.values) Total
+ = Item. Price * Item. Quantity;
return total;
}
public void Setquantity (string itemId, int qty)
{
Cartitems[itemid]. Quantity = qty;
}
public int Count
{get
{cartitems.count}
}
public void Add (string itemId)
{
cartiteminfo cartitem;
if (!cartitems.trygetvalue (itemId, out cartitem))
{
item = new item ();
ItemInfo data = Item. GetItem (itemId);
if (data!= null)
{
CartItemInfo newitem = new CartItemInfo (itemId, data. ProductName, 1, (decimal) data. Price, data. Name, data. CategoryID, data. PRODUCTID);
Cartitems.add (ItemId, newitem);
}
else
cartitem.quantity++;
}
Other methods slightly;
}
The cart class is responsible for storing the contents of the shopping cart through a Dictionary object, and defines add, Remove, clear and other methods to realize the management of the shopping cart content.
As I mentioned earlier, the domain object in the PetShop business logic layer is just a simple encapsulation of the data object, but the separation hierarchy still plays an important role in the architecture design. Take the Add () method of the Cart class as an example, introduce the PetShop.BLL.Item domain object inside the method, and call the GetItem () method of the Item object. If you do not encapsulate the item object in the business logic layer, but call the item data object directly from the data access layer, you need to call factory object's factory method to create the PetShop.IDAL.IItem interface type object to ensure a weak dependency between levels. Once the item object of the data access layer is called multiple times, it will result in duplicate code, which is not only modified and extended by the program, but also causes the program structure to grow into a bloated situation.
In addition, the encapsulation of the domain object to the data Access layer data object also facilitates the representation layer's call to the business logic layer. In a three-tier architecture, the presentation layer should be "ignorant" of the data access layer, thus reducing dependencies between layers and layers and effectively avoiding the consequences of "cyclic dependency".
It is worth discussing the total property of the cart class. The value is obtained by traversing the shopping cart collection and then accumulating the product of the price and the quantity of the product. This clearly simplifies the business logic and does not adequately consider the need for expansion. In fact, the algorithm for getting the total price of a shopping cart is, in most cases, just one of those strategies, and we should consider discounting. For example, when the total price exceeds 100 yuan, you can give the customer a certain discount, which is related to the site's promotional programs. In addition to discounts to the promotional program, the site can also consider gift promotion strategy, so we need to introduce strategy mode, define interface Ionsalestrategy:
Public interface Ionsalestrategy
{
decimal calculatetotalprice (Dictionary cartitems);
}
So, we can define a constructor with parameters for the cart class:
Private Ionsalestrategy M_onsale;
Public Cart (Ionsalestrategy OnSale)
{
M_onsale = OnSale;
}
Then the total property can be modified to:
Public decimal Total
{get
{m_onsale.calculatetotalprice (cartitems);}
}
In this way, the cart class can effectively support the promotional programs launched by the website, but also in line with the open-closed principle. Similarly, this design mode is also the embodiment of domain model model. The modified design is shown in Figure 5-1:
Figure 5-1 Introducing Strategy mode
As a business-oriented e-business architecture, it covers a range of areas that are familiar to most designers and developers, so in this case the collaboration with the domain experts seems less important. However, if we are to develop a successful ecommerce website, cooperation with field experts is still essential. In order management, if you consider complex business applications, you need to manage order tracking (tracking), cooperation with online banking, account security, inventory management, logistics management, and customer relationship management (CRM). The entire business process is covered such as e-commerce, banking, logistics, customer relations and many other fields, if there is no domain experts to participate, the design of the business logic layer may be "nationalists awry".
5.4 Communication with the data access layer
The business logic layer needs to communicate with the data access layer to access the database through the data access layer, so there is a dependency between the business logic layer and the data access layer. When the data access layer introduces the interface assembly and the design of the Data Factory, the relationship between the two can be weakly dependent. We can see from the reference assemblies in the business logic layer that the BLL module does not refer to Sqlserverdal and Oracledal assemblies. In the business logic layer, the invocation of the data object in the data access layer uses the polymorphic principle to define the abstract interface type object, and then uses the factory object's factory method to create the concrete data object. As shown in the PetShop.BLL.PetShop domain object:
Namespace PETSHOP.BLL
{public
class Product
{
////Create IProduct interface type instance based on factory object;
private static readonly iproduct dal = PetShop.DALFactory.DataAccess.CreateProduct ();
Invokes the interface method of the IProduct object Getproductbycategory ();
Public IList
getproductsbycategory (String category)
{
//New List object if empty;
if (string. IsNullOrEmpty (category)) return to
new List ();
Accessing the database by data object of data access layer;
Return DAL. getProductsByCategory (category);
}
Other methods slightly;
}
In the domain object product class, Use the factory class dalfactory.dataaccess of the data access layer to create an instance of the PetShop.IDAL.IProduct type so that you can unbind the Sqlserverdal or oracledal of the specific assembly. As long as the Petshop.idal interface method is unchanged, even if the implementation of the Idal interface module is modified, it will not affect the implementation of the business logic layer. This loosely coupled relationship can support the scalability of the schema to the fullest extent possible.
The domain object product actually completes the encapsulation of the data object product, the exposed interface method is consistent, precisely through encapsulation, so that the presentation layer can completely detach from the database and the data access layer, the caller of the presentation layer only needs to focus on the implementation logic of the business logic layer, As well as the interface and invocation methods exposed by the domain object. In fact, as long as the design is reasonable, standardize the interface methods at all levels, the three-tier architecture design can be separated from the development of different developers at the same time, this can effectively use development resources, shorten the project development cycle.
5.5 Interface-oriented design
Perhaps the business logic is simpler because, in the design of the business logic layer, it does not uphold the idea of interface design in the data access layer. In addition to completing the abstraction of the Insert order policy, the entire business logic layer is implemented in the BLL module only, without defining an abstract interface for the domain object. Therefore, there is a strong dependency relationship between the presentation layer of PetShop and the business logic layer, and if the requirements change in the business logic layer, the implementation of the presentation layer will inevitably be affected. The only consolation is that, because we use a layered architecture to the user interface and business domain logic completely separate, once the user interface changes, such as the B/s architecture modified to C/s architecture, then the business Logic Layer implementation module can be fully reused.
However, the ideal approach is still interface-oriented design. Based on the analysis of the asp.net cache in the 28th chapter, we can divide the proxy class and the utility class in the presentation layer into the business logic layer, modify these static classes as instance classes, and abstract the methods related to the business domain in these classes as interfaces. Then create an abstract factory like the data access layer. By means of "dependency injection", the dependency of specific domain object classes is lifted, so that the presentation layer relies only on the interface assembly of the business logic Layer and the factory module.
So, does this design have the suspicion of "excessive design"? We need to depend on the requirements of the business logic. In addition, if we need to introduce caching mechanisms to create proxy classes for domain objects, it is particularly necessary to establish interfaces for domain objects. We can create a specialized interface module IBLL to define the interface of the domain object. Take the product domain object as an example, we can establish the IProduct interface:
Public interface iproduct
{
IList getproductbycategory (String category);
IList getproductbycategory (string[] keywords);
ProductInfo getproduct (string productId);
You can introduce dependencies on the IBLL assembly in the BLL module, the domain object product is defined as follows:
public class Product:iproduct
{public
IList getproductbycategory (String category) {//implementation abbreviated;}
Public IList getproductbycategory (string[] keywords) {//implementation slightly;}
Public ProductInfo getproduct (string productId) {//implementation abbreviated;}
}
We can then establish a dedicated assembly Bllproxy for the proxy object, which not only introduces the dependency on the IBLL assembly, but also relies on the BLL assembly. At this point the proxy object productdataproxy is defined as follows:
Using PETSHOP.IBLL;
Using PETSHOP.BLL;
Namespace Petshop.bllproxy
{public
class productdataproxy:iproduct
{public
IList Getproductbycategory (String category)
{
Product Product = new product ();
Other implementations slightly;
}
Public IList getproductbycategory (string[] keywords) {//implementation slightly;}
Public ProductInfo getproduct (string productId) {//implementation abbreviated;}}}
This design is the typical proxy pattern, and its class structure is shown in Figure 5-2:
Figure 5-2 Proxy Mode
Referring to the design method of the data access layer, we can establish abstract factories for domain objects and proxy objects, configure related configuration sections in Web.config, and then use reflection technology to create concrete object instances. In this way, the presentation layer can rely solely on the PETSHOP.IBLL assembly and the factory module, so that the dependencies between the presentation layer and the specific domain object can be lifted. The relationship between the presentation layer and the modified business logic layer is shown in Figure 5-3:
Figure 5-3 The relationship between the modified business logic layer and the presentation layer
Figure 5-4 is a hierarchical diagram of the original design of PetShop 4.0:
Figure 5-4 The relationship between the presentation layer and the business logic layer in PetShop 4.0
By comparing figure 5-3 with Figure 5-4, although the latter is relatively simpler, regardless of the number of modules or the relationship between modules, the Web Component component is strongly coupled to the business logic layer, and this design is not conducive to business expansion and demand change. By introducing the interface module IBLL and the Factory module Bllfactory, the dependence of BLL with the concrete module is relieved. This design for the business logic of relatively complex systems, more in line with object-oriented design ideas, conducive to the establishment of a removable, replaceable "drawer" type three-tier architecture.
The above is PetShop's business logic layer design all content, hope can give everybody a reference, also hope everybody support cloud habitat community a lot.