Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the functions of Service and Manager

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "what is the role of Service and Manager". In daily operation, I believe many people have doubts about what is the role of Service and Manager. Xiaobian consulted all kinds of information and sorted out simple and easy operation methods. I hope to help you answer the doubts about "what is the role of Service and Manager"! Next, please follow the small series to learn together!

1. Background

When it comes to application layering, most people will think that this is not very simple, that is, three layers of controller, service and mapper. It seems simple, many people actually do not divide their responsibilities, in a lot of code, controller does more logic than service,service is often regarded as transparent, this is actually a lot of people develop code do not notice the place, anyway, the function can also be used, as for where to put it does not matter. This often causes the code behind can not be reused, hierarchy confusion, maintenance of subsequent code is very troublesome.

Indeed, in the eyes of these people, layering is just a form. The code of the predecessors was written like this, and the code of other projects was written like this, so I also wrote it like this.

However, in real team development, everyone's habits are different. The code written must carry their own labels. Some people are used to writing a lot of business logic in controller, and some people are used to calling remote services between services. This leads to a completely different development code style for everyone. When others modify it later, they will see that the code I wrote by this person is completely different from my usual habits. When modifying it, they will change it according to their previous habits. Or follow the seniors, this is a difficult choice, once the choice is wrong, your descendants and maintain your code, I am afraid you will curse.

So a good application layering needs to have the following:

facilitate maintenance and extension of subsequent code;

Layered effects need to be accepted by the entire team;

The boundaries of responsibilities at each level are clear.

2. Application of layered model

In project development, a good engineering architecture is a must. Engineering architecture is like a skeleton, writing code is to add flesh to this skeleton, this skeleton will affect the overall module division, functional division, that is, will affect the decoupling and aggregation of code, will largely determine whether a project is written well.

What I want to share here is the engineering architecture that I personally adopted when developing, and related thoughts. Different people have different understandings of engineering architecture. In fact, it is difficult to distinguish which is good and which is bad. As long as it conforms to their own design ideas and can be effectively developed, it is a good architecture.

2.1 stratification

As follows:

Application Hierarchy Diagram

Insert a mouth here, the flowchart tool I use here is ProcessOn, an online drawing tool, very suitable for drawing various schematics, excellent experience, if you want to try, you can use my invitation link to register (read the original) Use ~

Next I will explain my understanding and design of the layers from the bottom up, as well as the layers I added myself.

2.2 Common tool layer

The generic tools layer is actually a business-independent, generic tool class, such as date processing tools, serialization and deserialization tools for some data formats. Similar to apache commons package and guava package.

2.3 hierarchical domain model

Domain models, which are all kinds of data entities we used to see, are called anemic domain models in DDD terms.

The anemic domain model acts only as a data carrier, with only getter/setter methods and no business methods.

For the hierarchical domain model, the specification is further divided as follows:

DO(Data Object) : Data object, mapping to data source data, such as database tables, ElasticSearch index data structure. The package is usually named data.

DTO(Data Transfer Object) : Data transfer object, object transferred outward by business layer. If multiple queries are needed to obtain different data objects in a certain service, these multiple data objects will finally be combined into a DTO and transmitted to the outside. The package is named dto.

BO(Business Object) : Business object, an object that encapsulates business logic output by the Service layer. That is, besides data, the object also contains certain business logic, which can also be said to be a congestion domain model. But I don't usually use it.

AO(Application Object) : Application object, an abstract reusable object model between the Web layer and the Service layer, very close to the display layer, and the degree of reuse is not high. Less used.

VO(View Object) : Display layer object, usually an object transferred by the Web to the template rendering engine layer. Most of the current projects are separated from the front and back, and the back end only needs to return JSON, so it can be understood that JSON is the "template" that needs to be rendered. I usually call this object xxxResponse and the package response.

Query : Data query object, data query object, each layer receives query requests from the upper layer. In fact, it is generally used for Controller to accept passed parameters, you can name them xxxQuery, and I personally like to put the parameters in the request body (i.e.@RequestBody) wrapped as xxxRequest, and if you use the parameters transmitted by the form (i.e.@RequestParam) wrapped as xxxForm, and placed under the package request and package form respectively.

In fact, the anemia domain model is only used as a carrier of data. At first, I felt that there was no need to classify it specifically. Basically, it was thrown into a package. However, when the project scale increased, various data entities began to increase and gradually became chaotic. The classification of data objects is to better define the role of each data and to be able to quickly locate the corresponding data objects in the future.

2.4、Helper

Development will encounter some very basic, common business logic, for example, we may generate a unique account id based on each user's information. Or if there is a user ranking requirement, we will calculate a score from the user's relevant information, and then rank according to this score. Then we may write this logic under the User data object or other corresponding data object.

Personally, I don't want data objects to contain business logic, so I'll pull out these common business logics and put them in Manager for unified management. For example, the logic to generate account id will be placed in AccountIdGenerator, and the logic to calculate ranking score will be placed in RankCalculator.

I classify these classes as Helpers, which provide the underlying business computation logic. And why not put it in the general tools layer? Because these Helpers are actually dependent on a specific domain, that is, a specific business. General tools are business-independent and can be referenced by any system as long as it is needed.

2.5、DAO

DAO does not need to be explained too much, data access object, used to access the database. But I personally don't limit DAO to databases. For interactions with different data sources, such as HBase, ElasticSearch, local cache and even Redis, I define DAO access.

Such a definition is actually intended to separate the logic of the data CURD from the business logic, and the CRUD will be encapsulated in the DAO, and the business logic will be placed in the business layer.

Before taking over a project, the project regarded Redis as middleware and encapsulated the related logic in xxxRedisService, including CRUD and some business logic. With the development of the project, some businesses that can actually be classified together have become placed in RedisService, some in Service at the business level, which can be imagined to be very chaotic and lead to the emergence of some BUGs.

2.6 Service and Manager

The role of Service need not be explained much, it is the encapsulation layer of specific business logic.

Specifically, Manager is defined as follows:

For the layer encapsulated by the third-party platform, pre-processing returns results and conversion exception information

Subsidence of common capabilities of Service layer, such as caching scheme and middleware common processing

Interact with DAO layer and reuse multiple DAO combinations

Manager can be understood as encapsulation of general logic, avoiding mutual calls between Service and Service, and management of general logic.

In development, we often encounter that a certain service in AService can be provided to BService invocation, so that BService invokes the method of AService, thinking that there is a common service between Services. In fact, there is no common business between Services, but there is a common logic, which should be extracted and placed in Manager. No matter what kind of engineering architecture is good, I don't agree with the call between Service and Service.

In actual development, I'll break down Manager a little bit more. It is roughly divided into the item class, which encapsulates the general service sunk by Service.

The other is a class that tends to be instrumental and computational, such as a business that uses policy patterns, and the policy class that is written belongs to this class.

I'll annotate the business class with @Service and the tool class with @Component. The reason for this is to avoid mutual invocation and coupling between services.

Here you might wonder, why not put Helper logic in the Manager layer as well? The reason is that Helper logic is more basic than Manager, and it is possible to call Helper logic in DAO. If it is placed in Manager, there will be a problem that the bottom layer depends on the upper layer.

2.7 interface layer

The final layer is the one exposed to external calls. It can be a Controller in Spring architecture or gRPC.

This layer will organize and invoke the services we define to process the business.

3. Advantages and disadvantages of hierarchical model

No matter what kind of engineering framework, there will be its advantages and disadvantages. In selecting an engineering framework, it is actually a measure of advantages and disadvantages.

3.1, advantages

In fact, no matter what architecture, especially for business engineering, the most desirable architecture is decoupling and cohesion.

Through layering, each module in the project is decoupled and cohesive to a certain extent, and the dependency relationship is very clear. No matter how to write it, as long as it conforms to the convention, the upper layer always depends on the lower layer. Moreover, the layered protocol is very simple, and in most cases, the protocol can be well observed in the case of multi-person cooperation.

3.2 Disadvantages

Simplicity is both a plus and a minus. Although the layering is decoupled to a certain extent, the granularity is very coarse. As long as there is no situation where the lower layer depends on the upper layer, it can be considered as conforming to the specification. In this case, it is easy to lead to the dispersion of code and the fragmentation of functions. The code that is obviously the same type of business function is scattered among multiple classes and multiple levels. As the project iterates, it gets big, and then it gets messy, and then there's a round of refactoring.

It boils down to being too lax, making it easy for developers to just write anywhere in the project, and it's easy to duplicate code by copying and pasting a lot.

In the software engineering class offered by the school, design a system, first understand the organizational architecture, then extract the data flow from it, and then extract the business flow from the data flow, and develop according to the business flow. With a hierarchical model, development can often begin in the data flow. With a hierarchical model, each business can be simply abstracted into the flow of data between layers.

This can be said to be an advantage, simplifying the understanding of the business and achieving rapid development. I have also done this under a relatively tight schedule. After scanning the business and conceiving the flow of data flow, I started. But this is also a very serious flaw, I have seen a lot of functional BUG, is due to insufficient understanding of the business, and because there is no full understanding of the business process after development, subsequent expansion and repair, it seems to be constant tinkering.

4. Comparison with congestion domain model

Since we are talking about engineering architecture, we have to mention the concept of DDD.

Why did I say "contrast to congestion domain model" instead of "contrast to DDD"? Because DDD is a higher level concept than the hierarchical model, it is a product service, a guiding ideology for the entire team development, rather than a specification on engineering code.

DDD can be divided into two major directions, one is the strategic level, that is, mentioned earlier is a kind of development guiding ideology, define, divide the service domain, specify the unified language to improve communication efficiency, etc., which can also be used in the project development using the hierarchical domain model. If you want to compare it to the hierarchical model, it's actually the tactical level of DDD, the congestion domain model.

The congestion domain model is actually a return to object-oriented thinking. In the current hierarchical model, even if it is written in Java, an object-oriented language, it is generally a procedural programming, called transaction script in DDD.

Congestion domain model is heavy domain, light service. Taking the previous example of generating account id and ranking, in the congestion domain model, the User class will have generateAccountId and ranking methods to complete this logic.

Complete object-oriented, you can give full play to the object-oriented characteristics. The object-oriented features in the book are: inheritance, polymorphism, encapsulation. The former two can realize normalization, make the module generalization universal, encapsulation will make the module division clear, can realize decoupling and cohesion well. Using a congested domain model rather than a hierarchical model solves the problem of code fragmentation mentioned above.

The strength of the congestion domain model is the strength of object-orientation, but the weakness of object-orientation also becomes the weakness of this model. First of all, everything can be abstracted, which seems to me to be a false proposition, because there are always things in the real world that are difficult to abstract, or that are not elegant to abstract, and there is always a sense of hard abstraction.

There is a good answer in Zhihu, describing the disadvantages of object-orientation.

I believe that many people will search for examples of congestion domain model practice when they first come into contact with DDD. In fact, when learning Java Web development at school, the MVC structure written in the book is actually a congestion domain model to a certain extent. In addition to being a carrier of data, Model also contains business logic, and the business is completed through the selection and invocation of Model by Controller. If this kind of structure is used for development, when the project is huge, I think the first problem encountered should be the dependency problem. Complex business must involve all aspects. Naturally, there will be complex dependency relations, and even very "dirty" implementations will be produced in order to complete the business, which is inevitable.

Personally, I think the congestion domain model is still only suitable for individuals, small teams, such as 2 to 3 people, because abstraction itself is a very complex process, with the iteration of requirements, the previous abstraction may not be correct, if in a more multi-person multi-person collaboration, all kinds of strange writing will appear, there will inevitably be a random "ground" writing situation, this situation is more fatal than in the hierarchical model.

At this point, the study of "what is the role of Service and Manager" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report