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

How to understand front-end separation and front-end modularization of software architecture

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to understand front-end separation and front-end modularization of software architecture". The content in this article is simple and clear, and it is easy to learn and understand. let's study and learn "how to understand front-end separation and front-end modularization of software architecture".

Front and rear separation architecture

Before formally explaining the separation of front and background architectures, let's take a look at the architectural patterns of traditional software development many years ago.

Why are the front and rear ends separated?

I still remember that when I was in college a few years ago, when I was a beginner in Java Web development, the textbook introduced the very traditional architecture model of JSP + Servlet. At this time, the front-end and back-end business logic codes were in the same project and had not yet been separated. This development mode belonged to Model1 mode. Although the logic function and display function were separated, the view layer and control layer were implemented by JSP pages. The view layer and the control layer are not separated.

With the deepening of learning and the increasingly popular enterprise application development, we gradually abandon this technology selection, and begin to use a number of open source frameworks in the project, such as Spring + Struts/Spring MVC + Hibernate/Mybatis and so on. Because of the superiority of the framework and good encapsulation, this set of development framework combination has quickly become the best choice in the development of various enterprises. The emergence of these frameworks also reduces the repetitive coding work of developers, simplifies development, speeds up the development progress, and reduces the difficulty of maintenance, followed by the hot development mode behind this technical framework, namely MVC development mode, which is designed to overcome the shortcomings of Model1.

The specific meaning of MVC is: Model + View + Controller, that is, model + view + controller

Model model layer: it is often written in JavaBean, it accepts the data requested by the view layer, then carries on the corresponding business processing and returns the final processing result, it bears the core responsibility, and uses the characteristics of JavaBean to achieve code reuse and expansion as well as bring convenience to maintenance.

View view layer: represents the interface that interacts with the user and is responsible for the collection and display of data, usually implemented by JSP.

Controller control layer: the control layer receives the request from the client, then transmits the request to the model layer and tells the model layer what function module should be called to deal with the request. It will coordinate the work between the view layer and the model layer and act as an intermediate hub. It is generally implemented by Servlet.

The workflow of MVC is shown in the following figure.

At the same time, the project development is divided into three layers: control layer, business layer and persistence layer. The control layer is responsible for receiving parameters, calling the relevant business layer, encapsulating data, routing and rendering the data to the JSP page, and then displaying the background data in the JSP page. I believe everyone is very familiar with this development model, whether it is enterprise development or personal project construction, this development model is everyone's first choice, but with the expansion of the development team and the continuous evolution of the project architecture. This development model is gradually falling short of its goals.

Next, let's analyze the pain points of this development model.

Pain Point 1: JSP efficiency

First of all, JSP must be run in a Servlet container (such as Tomcat,jetty, etc.), a compilation process is required when requesting JSP, and finally translated into Java classes and class files, which will take up PermGen space and also need a new class loader to load. JSP technology has a strong relationship with the Java language and Servlet, and can not be comparable to template engines or pure html pages in decoupling. Secondly, after each request for JSP, the response is the html page output by Servlet through the output stream, and it is not as efficient as using html directly. Because of the strong relationship between JSP and Servlet container, Nginx can not be directly used as the web server of JSP during project optimization, and the performance improvement is not high.

Pain point 2: the division of labor is not clear

The workflow in this development mode is usually: after the designer gives the page prototype design, the front-end engineer is only responsible for cutting the design drawing into html pages, and then the back-end development engineers need to convert html to JSP pages for logical processing and data display. In this working mode, the human error rate is higher, the task of the back-end developer is heavier, and the collaborative development of both parties is needed to modify the problem, which is inefficient. Once a problem occurs, the front-end developer is faced with a JSP page full of tags and expressions, and the back-end staff will be stretched by the front-end technology, which is not good enough when faced with style or interaction problems.

In some emergencies, there will also be hilarious phenomena such as front-end personnel debugging back-end code, back-end developers debugging front-end code, the division of labor is not clear, and the communication cost is high. Once some functions need to be reworked, front and back-end developers are needed. In this case, it is also disadvantageous to the late technical growth of front-end and front-end personnel. The back-end pursues high concurrency, high availability, high performance, security, architecture optimization and so on. The front end pursues modularization, component integration, smooth speed, compatibility, user experience and so on, but in the development mode of MVC, it is obvious that there will be some constraints on these technicians.

Pain point 3: not conducive to project iteration

At the beginning of the project, in order to launch the application quickly, it is a very correct choice to use this development mode to develop the Java Web project. At this time, the traffic is not large, the number of users is not high, and there will not be very stringent performance requirements, but with the continuous growth of the project, the number of users and request pressure will continue to expand, and the performance requirements for Internet projects are getting higher and higher. If the front and rear modules are still coupled together at this time, it is very unfavorable for subsequent expansion. For example, in order to improve the load capacity, we will choose to do a cluster to share the pressure of a single application, but the coupling of modules will make the space for performance optimization getting lower and lower, because the single project will become larger and larger. No reasonable split can not achieve the best optimization, or when the deployment of the release version is launched, obviously only the back-end code has been changed, and the front end also needs to be rereleased. Or it is obvious that only part of the page or style has been changed, and the back-end code needs to be released online together, which is a common bad phenomenon when the coupling is serious. Therefore, the original front-end coupling architecture pattern has gradually failed to meet the evolution direction of the project, and it is necessary to find a decoupling way to replace the current development mode.

Pain point 4: failure to meet business needs

With the continuous development of the company's business, only browser-side Web applications have gradually become inadequate. At present, in the era of rapid growth of mobile Internet, native App applications on mobile phones have become very mature. With the popularity of App software, more and more enterprises have joined in App software development, in order to seize business opportunities and enhance user experience as much as possible. Your company may not focus all its development resources on web applications, but develop multiple applications at the same time. In this case, the company's business lines may be several or some of the following:

Browser-side Web applications, iOS native App, Android native App, WeChat Mini Programs and so on may only be some of the products developed, but except for web applications that can be developed using the traditional MVC mode, none of them can be developed using this mode. For example, native App or WeChat Mini Programs all exchange data with the backend by calling RESTful api.

With the development of Internet technology, more and more technical frameworks have been put forward, the most revolutionary of which is the concept of front-end separation.

What is front and rear separation?

What is front-end separation, I think it should be understood from the following aspects.

Front and rear separation is a project development model.

When the business becomes more and more complex or there are more and more product lines, the original development model can no longer meet the business needs. When there are more and more products on the end, the presentation layer changes faster and more. At this time, the front and rear ends should be separated and abstracted to simplify the data acquisition process. For example, at present, it is commonly used for front-end staff to implement jump logic and page interaction, while the back-end is only responsible for providing interface data. The data between the two is exchanged by calling RESTful api, as shown in the following figure:

At this point, the HTML code will not need to be transferred to JSP for development, the front-end project is only responsible for the front-end part, and will not be mixed with any back-end code, so the code is no longer coupled. At the same time, the front-end project and the back-end project will no longer be seriously coupled. As long as the front and back end negotiate and define the interface specification and data interaction specification, the two sides can develop in parallel without interfering with each other, and the business will not be coupled. The two ends interact only through interfaces.

When developing projects in MVC mode, the back end is often overweight and the "control" is relatively large. It is not only responsible for handling back-end operations such as business logic and rights management, but also dealing with logic such as page jump. In the mode of separation of the front and back end, the back end has changed from an all-around dictator to an interface provider, and the front end not only deals with a small part of the business as before. The page jump is no longer handled and decided by the back end, the control of the whole project has been transferred from the back end to the front end, and the front end needs to deal with more.

The front-end project and the back-end project are separated, do not interfere with each other, and complete the functional requirements of the project through interfaces and data specifications, which is also a popular way of development at present.

Front and rear separation is a kind of personnel division of labor.

In the architecture mode of separation of front and rear ends, the background is responsible for providing data, and the front end is responsible for displaying and interaction. in this development mode, the division of responsibilities between front-end developers and back-end developers is very clear, and both sides perform their own duties. There will be no unclear boundaries, and practitioners will perform their own duties.

Front-end developers include Web developers and native App developers, while back-end developers refer to Java developers (take the Java language as an example). Different developers only need to pay attention to the projects they are responsible for. The backend focuses on the control layer (RESTful API), the service layer and the data access layer, while the frontend focuses on the frontend control layer and view layer. There will be no need for front-end staff to maintain part of the backend code, or back-end developers need to debug styles and other cases of unclear responsibilities and front-end coupling. Let's compare it with two project development process diagrams:

At this point, there will be front-end coupling in the development process. If there is a problem, the front end needs to be reworked and the back end also needs to be reworked, the development efficiency will be affected. Now, the schematic diagram of the process after the front and rear ends are separated is as follows:

After the front and rear ends are separated, server-side developers and front-end developers do their own things, and they do not interfere with each other. After the completion of the design, Web developers, App developers and back-end developers can all devote themselves to the development work and can achieve parallel development. The front-end developers and back-end developers have separate responsibilities. Even if there are problems, the repair of their respective problems will not affect and couple each other, and the development efficiency is high and meets the development needs of enterprises for multi-product lines.

Front and rear separation is an architectural pattern

After the separation of the front and rear ends, each end of the application can be packaged and deployed independently, and the deployment mode can be optimized. It is no longer a unified project between the front and rear ends and finally deployed into a deployment package. Take the Web application as an example. After the front-end project is deployed, it no longer depends on the Servlet container, but can use the Nginx server with greater throughput. The deployment method adopts dynamic and static separation, which not only improves the front-end access experience, but also reduces the pressure on the back-end server. Further optimization, you can use page cache, browser cache and other settings, you can also use products such as CDN to improve the access efficiency of static resources. For the back-end service, cluster deployment can be carried out to improve the response efficiency of the service, and further service-oriented splitting can also be carried out. Independent deployment maintenance and targeted optimization after the separation of the front and rear ends can speed up the overall response speed and throughput.

Front-end development process

When we go to understand something, first of all we need to understand its history in order to better grasp its future.

Primitive times

The world's first browser, NCSAMosaic, was developed by Netscape in 1994. Its original intention was to make it easy for researchers to access materials and documents (at this time, most documents were in the form of pictures). Every interaction in that era, button clicks and form submission, required a long wait for the browser to respond and then download a new page.

In the same year, PHP (Hypertext preprocessor) scripting language was developed to enable the MVC mode of data embedding templates. Similar practices in the same period are as follows:

PHP embeds the data directly into the HTML.

ASPX of ASP, embed C # code in HTML.

Java's JSP embeds data directly into a web page.

During this period, browser developers are mostly background developers, and most of the front-end and front-end developers are integrated. The general development process is as follows: the back-end receives a request from the browser-- > send a static page-- > send it to the browser. Even if there is a special front-end development, it is only using HTML to write the page template, CSS to give the page a good-looking layout. During this period, the role of the front end is limited, often just the role of the cutter.

Iron Age

In 1995, one of Netscape's bosses, Brandon Ikey, wanted to develop a Java-like scripting language to improve the display of browsers and enhance dynamic interaction. As a result, the boss drank beer and smoked a cigarette, and wrote this scripting language in more than ten days. It is very powerful, but the grammar is not like Java at all. In this way, the prototype of the front end is gradually formed: HTML is the skeleton, CSS is the appearance, and JavaScript is the interaction.

At the same time, some companies such as Microsoft also developed their own scripting languages for their own browsers. There are a variety of browsers. Although there is a relatively unified ECMA standard, browsers have become popular in the market ahead of the standard and become a de facto standard. As a result, front-end engineers now have to deal with browser compatibility (the evil IE series) when doing some old government projects.

In any case, the front-end development can write some logic code, and it is no longer a low-end development that can only draw pages. With the emergence of AJax in 1998, the front-end development has moved from Web1.0 to Web2.0, and the front-end has developed from static display of pure content to a new era of dynamic web pages, rich interaction and front-end data processing. During this period, two well-known interactive and dynamic browser products are.

Gmail (2004)

Google Map (2005)

Due to the increasing demand for dynamic interaction and data interaction, an excellent cross-browser js tool library such as jQuery (2006) has been derived, which is mainly used for DOM operation and data exchange. Some ancient projects, and even large projects developed in recent years, are still using jQuery, so much so that the jQuery library is still being updated, although it is far inferior to excellent front-end libraries such as React and Vue in terms of volume.

Information age

Since 2003, the front-end development has gone through a relatively stable period, and the major browser manufacturers have not done anything else except to update their browser products step by step. But we programmers can't stand loneliness, industrialization promotes the rapid arrival of information, the amount of data presented by browsers is getting larger and larger, the demand for dynamic interaction of web pages is more and more, the disadvantages and bottlenecks of JavaScript through the operation of DOM are becoming more and more obvious (frequent interactive operations, resulting in page stutters), it becomes more and more difficult to improve page performance only from the code level. So the good bosses did some earth-shaking little things:

In 2008, Google's V8 engine was released, ending the Microsoft IE era.

In 2009, AngularJS was born and Node was born.

ReactJS was born in 2011.

VueJS was born in 2014.

Among them, the emergence of V8 and Node.JS enables front-end developers to write background systems with familiar syntax sugar, providing the front-end with the opportunity to achieve full-stack development using the same language (JavaScript is no longer a scripting language that can only write page interactions). The emergence of MVVM front-end frameworks such as React, Angular and Vue makes the front-end realize the real application of the project (SPA single-page application), no longer rely on background developers to deal with page routing Controller, and realize the self-management of page jump. It also promotes a complete separation between the front end and the back end (front-end projects are deployed independently and no longer rely on similar template file directories).

As for why the MVVM framework can improve the rendering performance of the front end, here is a brief description of the principle, because a large number of DOM operations are the main culprit of the performance bottleneck, then through a certain analysis and comparison of algorithms, it is feasible to achieve the minimum DOM overhead under the same effect. Frameworks such as React and Vue are mostly realized through this kind of idea, and the specific implementation can take a look at the relevant materials. The separation of front and rear ends has also led to some changes in the division of labor at the front end.

The back-end developers pay more attention to data services, while the front-end is responsible for presentation and interaction. Of course, the corresponding learning cost is also increasing, and the emergence of Node.JS also makes it possible for front-end and front-end development together. Many big companies have tried to use Node.JS as the intermediate data transfer layer before and after 2015, so that the back-end can focus more on data services and governance.

The development process of front-end modularization

Since the release of Node.js in May 2009, the front end has been able to do more and more things. In a short period of 10 years, the front end has moved from the era of slash-and-burn cultivation to the era of modularization and engineering. A hundred schools of thought contend in various front-end frameworks, and the front-end has won its own era.

Primitive times

Back in 2009, I remember that there was no popular front-end separation, many projects were still mixed together, and most of the front-end developers at that time were "cutters". The front end completes the static page, and the server colleagues complete the data embedding, that is, the so-called set of page operations. Whenever there is a similar function, it will go back to the previous page to copy and paste. Because it is on a different page, the class name needs to be changed. But the change is the same.

Over time, more and more repetitive code, whenever changing a small place, need to change a lot of code, it is extremely inconvenient, but also not conducive to large-scale engineering development. Although excellent front-end frameworks such as Angular and Avalon are slowly emerging in the market, considering that SEO and maintenance personnel are not easy to recruit, many companies still choose to be stable and make web pages in the form of a set of pages, which is no small obstacle to the engineering and modularization of the front end.

The emergence of build tools

However, with Node being highly respected, a large number of build tools have emerged on the market, such as Npm Scripts, Grunt, Gulp, FIS, Webpack, Rollup, Parcel, and so on. Building tools liberate our hands and help us deal with some repetitive mechanical work.

To take a simple example: we wrote a piece of code in ES6 that needs to be executed in the browser. However, because browser manufacturers are very conservative about browser updates, a lot of ES6 code can not be run directly on browsers. At this time, we can never manually change the ES6 code to ES5 code. As a result, the following transformation occurs.

/ / pre-compilation [1Jing 2jue 3] .map (item = > console.log (item)) / / after compilation [1Jing 2jue 3] .map (function (item) {return console.log (item);}); / / after code compression [1Jing 2J 3] .map (function (a) {return console.log (a)})

By doing the above, we can use the latest ECMAScript syntax when writing the front-end code, and compress the size of the code as much as possible, so that the browser can load static scripts more quickly.

Traditional modularization

With the popularity of Ajax, front-end engineers can do more than just "cut the picture". Now front-end engineers can do more and more, there is a clear division of labor, and can carry out data transfer with server-side engineers. The traditional modularization mentioned here is not post-modern modularization, the early modularization is without any tools, it is purely the structure of the code completed by JavaScript. In traditional modularization, we mainly extract some reusable code into common methods for unified maintenance and management, such as the following code.

Function show (id) {document.getElementById (id) .setAttribute ('style', "display: block")} function hide (id) {document.getElementById (id) .setAttribute (' style', "display: none")}

Then, we encapsulate these utility functions in a JS script file and introduce them where they are needed.

However, this approach will give rise to two big problems, one is the pollution of global variables, and the other is that manual maintenance of dependencies between modules will cause code confusion.

For example, when our project is maintained by more than a dozen or even dozens of people, it is inevitable that someone will add new methods to the common components, such as show, once the method is overridden, the people who use it will get different results than expected, resulting in global variable pollution. Another problem is that because the dependencies between common scripts in real projects are complex, for example, c scripts rely on b scripts, and a scripts rely on b scripts, so we should pay attention to this when we introduce it.

It must be introduced in this way to ensure that the a script runs properly, otherwise an error will be reported. For this kind of problem, how should we solve it?

Pollution of global variables

There are two ways to solve this problem. First, let's talk about the ways to cure the symptoms rather than the root of the problem. We develop documents through team specification. For example, I have a method that is used in the shopping cart module, which can be written as follows.

Var shop.cart.utils = {show: function (id) {document.getElementById (id) .setAttribute ('style', "display: block")}, hide: function (id) {document.getElementById (id) .setAttribute (' style', "display: none")}}

In this way, we can effectively avoid the pollution of global variables, write the method to the object, and then call it through the object. In technical terms, this is called the specification of namespaces, but if there are more variable names in this module, it will be more cumbersome, and it will be a long list, so I call it a temporary cure rather than a permanent cure.

There is also a more professional method to complete the closure encapsulation by executing the function immediately. In order to solve the problem of encapsulating variables in the package, it is a good way to execute the function immediately, which is also used by many early developers, as shown below.

(function () {var Cart = Cart | {}; function show (id) {document.getElementById (id) .setAttribute ('style', "display: block")} function hide (id) {document.getElementById (id) .setAttribute (' style', "display: none")} Cart.Util = {show: show, hide: hide}) ()

The above code, through an immediate execution function, gives the module an independent scope, and configures our module through global variables to achieve the purpose of modularization.

Current modularization scheme

Let's start with the CommonJS specification. After the release of Node.JS, the CommonJS modular specification has been used in project development. It has several concepts to explain.

Each file is a module, it has its own scope, the variables and functions defined internally are private and invisible to the outside.

The module variable inside each module represents the current module, which is an object

The exports attribute of module is the external interface. Loading a module is actually loading the module.exports attribute of the module.

Use the require keyword to load the corresponding module. The basic function of require is to read and execute a JavaScript file, and then return the exports object of the modified module. If not, an error will be reported.

Let's take a look at the example, and let's modularize the code mentioned above through CommonJS.

Module.exports = {show: function (id) {document.getElementById (id) .setAttribute ('style', "display: block")}, hide: function (id) {document.getElementById (id) .setAttribute (' style', "display: none")}} / / you can also output a single method module.exports.show = function (id) {document.getElementById (id) .setAttribute ('style') "display: block")} / / introduced var utils = require ('. / utils') / / use it utils.show ("body")

In addition to the CommonJS specification, there are several modular patterns that can only be seen in old projects, such as the AMD (Asynchronous Module Definition) specification represented by require.js and the CMD (Common Module Definition) specification represented by sea.js written by the Yubo team.

The characteristic of AMD is to load the module in one step, but only if all dependencies are loaded completely in the first place. The characteristic of CMD is that it relies on latency and loads only when needed.

AMD

First, let's take a look at how to write the above modular code through the require.js of the AMD specification.

Define (['home'], function () {function show (id) {document.getElementById (id) .setAttribute (' style', "display: block")} function hide (id) {document.getElementById (id) .setAttribute ('style', "display: none")} return {show: show, hide: hide};}); / / load module require ([' utils'], function (cart) {cart.show ('body')) })

Require.js defines a function define, which is a global variable and is used to define modules. Its syntax specification is as follows:

Define (id, dependencies, factory)

Id: it is an optional parameter that identifies the module

Dependencies: the array of module names that the current module depends on. For example, the above module relies on the home module, which solves the problem of the chaotic dependency relationship between the modules mentioned earlier. This parameter can be used to load the front-end dependent module.

Factory: the module initializes the function or object to execute.

Require ([dependencies], function () {})

Then, use require to introduce in other files. The first parameter is the dependent module array, and the second parameter is a callback function. When the previous dependent module is successfully loaded, the callback function will be executed, and the loaded module will be passed into the function in the form of parameters for other operations.

Thank you for your reading. the above is the content of "how to understand front-end separation and front-end modularization of software architecture". After the study of this article, I believe you have a deeper understanding of how to understand front-end separation and front-end modularization of software architecture, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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

Development

Wechat

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

12
Report