In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you the "sample analysis of business logic layer design in PetShop", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let the editor lead you to study and learn the article "sample analysis of business logic layer design in PetShop".
Fifth, the design of business logic layer of 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 system design related to business requirements, such as the formulation of business rules and the implementation of business processes, that is to say, it is related to the Domain logic that the system should deal with. in many cases, we also call the business logic layer the domain layer. For example, in his book Patterns of Enterprise Application Architecture, Martin Fowler divides the entire architecture into three main layers: presentation layer, domain layer, and data source layer. As the pioneer of domain-driven design, Eric Evans divides the business logic layer into application layer and domain layer, and further separates the solution of domain logic from domain logic through layering.
The position of the business logic layer in the architecture is very critical, it is between the data access layer and the presentation layer, and plays a connecting role in data exchange. Because the layer is a weakly coupled structure, the dependence between layers is downward, and the bottom layer is "ignorant" to the upper layer, and changing the design of the upper layer has no effect on the bottom layer of its call. If the idea of interface-oriented design is followed in hierarchical design, then this downward dependency should also be a weak dependency. Therefore, without changing the definition of the interface, the ideal hierarchical architecture should be an extractable and replaceable "drawer" architecture. Because of this, the design of the business logic layer is particularly critical to an architecture that supports extensibility because it plays two different roles. For the data access layer, it is the caller; for the presentation layer, it is the callee. The relationship between dependency and dependent is entangled in the business logic layer, so how to realize the decoupling of dependency is a task left to the designer besides the implementation of business logic.
5.1 cooperate with domain experts
The biggest obstacle to designing the business logic layer is not the technology, but the analysis and understanding of the domain business. It is hard to imagine that an architect who is not familiar with the business rules and processes in this area can design a system architecture that meets the needs of customers. It can almost be concluded that the design process of the business logic layer must involve domain experts. In the projects I have been involved in, the fields involved include power, semiconductors, automotive and many other industries. If there is a lack of experts in these fields, the design of software architecture, especially the design of business logic layer, is out of the question. The only exception to this conclusion is that the architect is also an expert in the field. However, as the saying goes, "A thousand troops are easy to get, but one will be difficult to find." it is very difficult for us to find such outstanding talents.
The role that domain experts play in the team is often referred to as Business Consultor (business consultant), who is responsible for providing advice related to the domain business, working with architects on architecture and database design, and writing requirements documents and design use cases (or user stories User Story). If you are in the test phase, you should also include writing test cases. Ideally, domain experts should be involved in the entire project development process, not just the requirements phase.
Domain experts can be consultants who are specially hired with deep attainments in the field, or clients who serve as demand providers. In extreme programming (Extreme Programming), customers are introduced into the entire development team as domain experts. It emphasizes the principle of on-site customers. On-site customers need to participate in all stages of project development, such as planning games, development iterations, coding testing, and so on. Since domain experts and designers and developers form a team, misunderstandings of requirements can be avoided throughout the development process. Even if the development of the project is not in line with the actual requirements, it can be corrected in time in the early stage of the project, so as to avoid unnecessary delay of the project and strengthen the control of the project process and cost. As mentioned by Steve McConnell in the preparation of the build activity, the time to find the error should be as close as possible to the time when the error was introduced. The longer the defect of the requirement lurks in the system, the more expensive it will be. If we can fully cooperate with domain experts in project development, we can avoid such a vicious chain reaction as much as possible.
Traditional software development models also attach importance to cooperation with domain experts, but this cooperation is mainly concentrated in the requirements analysis stage. The waterfall model, for example, places great emphasis on early planning and requirements research. However, this early planning method of planning in advance requires very high skills for architects and requirements investigators. it emphasizes the accuracy of requirements documents, once the analysis deviates, or the requirements change. When the project development enters the design stage, due to the lack of communication and cooperation mechanism with domain experts, developers can not estimate these errors and errors, so it is difficult to correct them in time. Once these problems spread like a cancer in the system and gradually exposed to developers, they have become an insurmountable mountain. We need to spend more manpower and material resources to correct these errors, resulting in an order of magnitude increase in development costs, and even lead to project delays. Of course, another good option is to give up the whole project. Such examples abound. In fact, most of the reasons for the "Waterloo" of project development are due to problems in business logic analysis.
Compared with the waterfall model, the iterative model is greatly improved because it allows the system requirements to be changed and optimized, and the whole iterative process is actually a cooperative process with domain experts by demonstrating the system functions generated by the iteration to the customer. in order to obtain feedback in time, and solve the problems in the iterative demonstration one by one to ensure that the system evolves in the direction that meets the needs of customers. As a result, iterative models often solve the problem of inadequate early planning, allowing them to be redesigned, recoded, and retested when defects are found and when requirements change.
No matter which development model is adopted, cooperation with domain experts will be the key to the success or failure of the project. This is based on the universal truth of software development that there are no constant requirements in the world. A classic saying is: "there are no constant requirements, the software in the world has been changed more than three times, and the owner of the only software that has been changed only twice is dead, dead on the way to modify the requirements." One word full of the cruelty and hardship of software development!
So how to strengthen cooperation with experts in the field? James Carey and Brent Carlson proposed the Innocent Questions model based on their experience in the IBM SanFrancisco projects they participated in, which means to "improve the quality of communication between domain 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 cooperation between domain experts and technical experts. After all, as a domain expert, he may not be familiar with software design methodology, nor do he have the ability of object-oriented development and architecture design. Similarly, most technical experts are likely to have little knowledge of the business areas involved in the project. If domain experts and technical experts cannot communicate effectively, the future of the whole project is in jeopardy.
The solutions proposed by the Innocent Questions model include:
(1) choose people who can live in harmony with others to form a development team.
(2) roles and powers are clearly defined
(3) clearly define the interaction points needed.
(4) keep the team close
(5) hire excellent people.
In fact, this has risen from a technical point of view to the level of team management. Just like basketball, even if your team brings together five of the best and most talented players in the world, it is still very difficult to win the game if you fight on your own. Teamwork and clear authority and responsibility are the guarantee of victory, and so is software development.
The basis for working with domain experts is to ensure that at least one domain expert is always retained in the development team. He can be a client of the system, a consultant of 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 a "Siberian cold snap".
Determine the roles, tasks and responsibilities of domain experts. Everyone on the team must be made clear about what role the domain expert plays in the team and what his responsibilities are. A qualified domain expert must have a deep understanding of the business domain, and he should be a person who can overlook the requirements of the whole system and take charge of the overall situation. In the process of project development, he will be responsible for the formulation of business rules and processes, communication with customers, research and discussion of requirements, and participate in the design of system architecture with designers. Documentation is the work that domain experts must participate in, whether it is requirements documents or design documents, as well as the writing of use cases, domain experts either give advice, or as the author, at least he should be an important member of the review committee.
Standardize terms and technical terms in the business domain. Domain experts and technical experts must communicate and communicate in a semantic environment that ensures that there is no ambiguity. If there are differences in understanding, we must resolve them in a timely manner and establish terminology standards through discussion. It is hard to imagine that people who do not speak two languages can cooperate happily with each other. The solution is to join a translator. Build a semantic bridge between domain experts and technical experts, so that they can understand and identify with each other. Another way is to conduct training activities within the team. Especially for developers, more or less understanding of some business domain knowledge is of great help to the development of the project. In the project development in the semiconductor field that I have participated in, the team specially invited experts from the semiconductor industry to conduct a comprehensive introduction and training on the business logic of the production process. As the saying goes, although we spend time on training, developers who have mastered business rules and processes can improve the progress of project development and save development costs as a whole.
Strengthen communication with customers. The customer can also serve as the team's domain expert, and the on-site customer principle of extreme programming is the best example. But the reality is not so perfect, when it is impossible to require the customer to become a fixed member of the development team, it is particularly important to hire or arrange a specialized domain expert to strengthen communication with the customer. The project can get timely feedback from customers through domain experts. Understanding the changed requirements through domain experts will reduce the possibility of demand errors to the maximum extent.
5.2 pattern application of business logic layer
In the book Enterprise Application Architecture pattern, Martin Fowler gives an overall overview of the architecture patterns of the domain layer (that is, the business logic layer). He divides the business logic design into three main patterns: Transaction Script, Domain Model and Table Module.
Transaction Script model regards business logic as a process, which is a typical process-oriented development model. The application of Transaction Script pattern does not need the data access layer, but uses SQL statements to access the database directly. To effectively manage SQL statements, you can put behaviors related to database access into a special Gateway class. The application of Transaction Script pattern does not require much object-oriented knowledge, and the simple and direct characteristics are the whole value of the pattern. Therefore, in many projects where the business logic is relatively simple, the Transaction Script pattern is widely used.
Domain Model pattern is the embodiment of typical object-oriented design idea. It fully considers the complexity and variability of business logic, introduces the idea of Strategy pattern and other design patterns, and realizes the extensibility of the pattern by establishing domain objects and abstract interfaces, and uses the inherent characteristics of object-oriented ideas, such as inheritance, encapsulation and polymorphism, to deal with complex and changeable business logic. The only thing that restricts the application of this pattern is the mapping between objects and relational databases. We can introduce ORM tools, or we can use Data Mapper schema to map relationships to objects.
Similar to the Domain Model pattern is the Table Module pattern, which also has the idea of object-oriented design, except that the object it obtains is not a simple domain object, but a DataSet object. If you establish a simple mapping relationship between a relational data table and an object, then the Domain Model schema is to create a domain object for each record in the data table, while the Table Module schema treats the entire data table 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 on the .net platform, both ADO.NET and Web controls provide fertile soil for the growth of the Table Module model.
5.3Business Logic layer Design of PetShop
PetShop introduces the Domain Model pattern into the design of the business logic layer, which is inseparable from the data access layer's support for data objects. Because PetShop does not go deep into the business logic of the pet online store, and omits many complex details of business logic, so the application of Domain Model model is not obvious. The most typical way should be the handling of Order domain objects, which encapsulates the insert order behavior by introducing the Strategy pattern. I have a detailed description of this point in Chapter 27, so I will not repeat it here.
It is supposed to be the core business logic layer in the system architecture design. Due to the simplification of the business process, the design of PetShop in this layer is somewhat poor. Although in the business logic layer, the relevant domain objects are defined for B2C business, these domain objects only complete the simple encapsulation of the data objects in the data access layer, and their purpose is only to separate the layers to support the expansion of various databases, while excluding SQL statements from the business logic layer to avoid the spread of SQL statements everywhere.
Besides the management of orders, what best embodies the business logic of PetShop includes the management of shopping cart (Shopping Cart) and Wish List. In the BLL module of PetShop, the Cart class is defined to take charge of the related business logic, 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 {return cartItems.Count;} public void Add (string itemId) {CartItemInfo cartItem If (! cartItems.TryGetValue (itemId, out cartItem)) {Item item = newItem (); 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;}
The Cart class is responsible for storing the shopping cart content through a Dictionary object, and defines Add, Remove, Clear and other methods to manage the shopping cart content.
I mentioned earlier that the domain objects in the PetShop business logic layer only complete the simple encapsulation of data objects, but this hierarchical approach still plays an important role in architecture design. Taking the Add () method of the Cart class as an example, the PetShop.BLL.Item domain object is introduced inside the method, and the GetItem () method of the Item object is called. If you do not encapsulate the Item object in the business logic layer, but directly call the Item data object in the data access layer, in order to ensure the weak dependency between the layers, you need to call the factory method of the factory object to create the PetShop.IDAL.IItem interface type object. Once the Item object of the data access layer is called many times, it will result in repeated code, which not only depends on the modification and expansion of the program, but also causes the program structure to grow into a bloated situation.
In addition, the encapsulation of the data object in the data access layer by the domain object is also beneficial to the call of the presentation layer to the business logic layer. In the three-tier architecture, the presentation layer should be "ignorant" of the data access layer, which not only reduces the dependency between layers, but also effectively avoids the consequences of "circular dependency".
What is debatable is the Total property of the Cart class. Its value is obtained by traversing the shopping cart collection and then accumulating the product of the price and the quantity of the goods. This obviously simplifies the business logic without fully taking into account the expansion of requirements. In fact, this algorithm to get the total price of the shopping cart is just one of the strategies in most cases, and we should also consider the discount. For example, when the total price exceeds 100 yuan, customers can be given a certain discount, which is related to the promotion plan of the website. In addition to the promotion plan that gives discounts, the website can also consider the promotion strategy of giving gifts, so it is necessary to introduce the Strategy model and define the interface IOnSaleStrategy:
Public interface IOnSaleStrategy {decimal CalculateTotalPrice (Dictionary cartItems);}
In this way, we can define a constructor with parameters for the Cart class:
Private IOnSaleStrategy Cart (IOnSaleStrategy onSale) {m_onSale = onSale;}
Then the Total property can be changed to:
Public decimal Total {get {return m_onSale.CalculateTotalPrice (cartItems);}}
In this way, the Cart class can effectively support the promotion plan launched by the website and comply with the open-close principle. Similarly, this design method is also the embodiment of the Domain Model pattern. The modified design is shown in figure 5-1:
Figure 5-1 introduces the Strategy pattern
As a B2C e-commerce architecture, the business areas involved are familiar to most designers and developers, so in this case, cooperation with domain experts is not so important. However, if we are to develop a successful e-commerce website, cooperation with domain experts is still essential. In terms of order management, if complex business applications are considered, it is necessary to manage order tracking (Tracking), cooperation with online banking, account security, inventory management, logistics management, and customer relationship management (CRM). However, the whole business process covers many fields, such as e-commerce, banking, logistics, customer relations and so on. Without the participation of domain experts, the design of the business logic layer may fail.
5.4 Communication with the data access layer
The business logic layer needs to communicate with the data access layer and uses the data access layer to access the database, so there is a dependency between the business logic layer and the data access layer. Under the premise of introducing interface assembly and data factory into the data access layer, the relationship between them can be weakly dependent. We can see from the reference assembly of the business logic layer that the BLL module does not reference the SQLServerDAL and OracleDAL assemblies. In the business logic layer, about the invocation of data objects in the data access layer, abstract interface type objects are defined by the principle of polymorphism, and then the factory methods of factory objects are used to create concrete data objects. As shown in the PetShop.BLL.PetShop realm object:
Namespace PetShop.BLL {public class Product {/ / create an instance of the IProduct interface type based on the factory object; private static readonly IProduct dal = PetShop.DALFactory.DataAccess.CreateProduct (); / / call the interface method GetProductByCategory () of the IProduct object; public IListGetProductsByCategory (string category) {/ / create a new List object if it is empty; if (string.IsNullOrEmpty (category)) return new List (); / / access the database through the data object of the data access layer; return dal.GetProductsByCategory (category) } / / other methods;}}
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, which frees you from the dependency on the concrete assembly SQLServerDAL or OracleDAL. As long as the interface method of PetShop.IDAL remains unchanged, even if the specific implementation of the IDAL interface module is modified, it will not affect the implementation of the business logic layer. This kind of loose weak coupling relationship can support the scalability of the architecture to the maximum extent.
The domain object Product actually completes the encapsulation of the data object Product, and their exposed interface methods are consistent. It is through encapsulation that the presentation layer can be completely separated from the database and data access layer. The caller of the presentation layer only needs to pay attention to the implementation logic of the business logic layer, as well as the interfaces and invocation methods exposed by the domain objects. In fact, as long as the design is reasonable and standardizes the interface methods at all levels, the design of the three-tier architecture can be developed by different developers at the same time, which can make effective use of development resources and shorten the project development cycle.
5.5 Interface-oriented Design
Perhaps because the business logic is relatively simple, the design of the business logic layer does not adhere to the idea of interface-oriented design in the data access layer. In addition to abstracting the insertion order policy, the whole business logic layer is implemented only by BLL modules, and there is no abstract interface defined for domain objects. Therefore, there is a strong dependency between the presentation layer and the business logic layer of PetShop. If the requirements in the business logic layer change, it will inevitably affect the implementation of the presentation layer. The only gratifying thing is that because we use a hierarchical architecture to completely separate the user interface from the business domain logic, once the user interface changes, such as changing the Bhand S architecture to the Cmax S architecture, then the implementation module of the business logic layer can be completely reused.
However, the most ideal way is still interface-oriented design. According to the analysis of ASP.NET cache in chapter 28, we can divide the Proxy class and Utility class under the presentation layer App_Code into the business logic layer, modify these static classes into instance classes, abstract the methods related to the business domain into interfaces, and then establish an abstract factory like the data access layer. Through the way of "dependency injection", the dependency is released from the specific domain object class, so that the presentation layer only depends on the interface assembly and factory module of the business logic layer.
So, does such a design have the suspicion of "over-design"? We need to depend on the requirements of the business logic. In addition, if we need to introduce a caching mechanism to create proxy classes for domain objects, it is particularly necessary to establish interfaces for domain objects. We can establish a special interface module IBLL, which is used to define the interface of domain objects. Taking the Product domain object as an example, we can establish an IProduct interface:
Public interface IProduct {IList GetProductByCategory (string category); IList GetProductByCategory (string [] keywords); ProductInfo GetProduct (string productId);}
Dependency on IBLL assemblies can be introduced in the BLL module, and the domain object Product is defined as follows:
Public class Product:IProduct {public IList GetProductByCategory (string category) {/ / implementation strategy;} public IList GetProductByCategory (string [] keywords) {/ / implementation strategy;} public ProductInfo GetProduct (string productId) {/ / implementation strategy;}}
We can then create a special assembly BLLProxy for the proxy object, which not only introduces a dependency on the IBLL assembly, but also on the BLL assembly. 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 implementation strategies;} public IList GetProductByCategory (string [] keywords) {/ / implementation strategies;} public ProductInfo GetProduct (string productId) {/ / implementation strategies;}
Such a design is a typical Proxy pattern, and its class structure is shown in figure 5-2:
Figure 5-2 Proxy mode
With reference to the design method of the data access layer, we can establish abstract factories for domain objects and proxy objects, configure relevant configuration sections in web.config, and then use reflection technology to create concrete object instances. In this way, the presentation layer can rely only on PetShop.IBLL assemblies and factory modules, thus releasing the dependency between the presentation layer and domain-specific objects. 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 relationship between the presentation layer and the business logic layer in PetShop 4. 0
By comparing figures 5-3 with figure 5-4, although the latter is relatively simple in terms of the number of modules and the relationship between modules, there is a strong coupling between the Web Component components and the business logic layer, which is not conducive to responding to business expansion and requirements changes. Through the introduction of the interface module IBLL and the factory module BLLFactory, the dependence on the specific module BLL is removed. For systems with relatively complex business logic, this design is more in line with the idea of object-oriented design, and is helpful for us to establish an extractable and replaceable "drawer" three-tier architecture.
The above is all the contents of the article "sample Analysis of Business Logic layer Design in PetShop". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.