2016 – my way to the front end: instrumentalization and Engineering

Time:2020-10-19

2016 – my way to the front end: instrumentalization and EngineeringSubordinate to the authorIntroduction and engineering practice of web front endThis paper is based on the author’s annual summary of last year2015 my way to the front end: data flow driven interface。 In addition, if you are interested in the overall programming technology system and thinking, please read another review article:2016 my way to technology: programming knowledge architecture

2016 - my way to the front end: instrumentalization and Engineering

preface

Twenty years of glory

2016 - my way to the front end: instrumentalization and Engineering

In recent years, with the improvement of browser performance and the surging wave of mobile Internet, web front-end development has entered an era of rapid progress and rapid change. This is the best era. We are always moving forward. This is also the worst time. Countless front-end development frameworks and technical systems compete with each other, making developers confused and even at a loss. The development of Web front-end can be traced back to 1991, when Tim Berners Lee publicly mentioned HTML description, and then in 1999, W3C released html4 standard. This stage is mainly BS architecture, and there is no so-called front-end development concept. Web page is just a handy work of back-end engineers, and server-side rendering is the main way of data transmission. In the next few years, with the development of the Internet and the proposal of rest and other architecture standards, the concept of front-end separation and rich client is increasingly recognized. We need to expand on the language and basic API. At this stage, a series of front-end auxiliary tools represented by jQuery have appeared. Since 2009, with the development and popularization of smart phones, the wave of mobile terminals is irresistible. The design concept of spa single page application is also popular. The related front-end modular, component-based, responsive development, hybrid development and other technical needs are very urgent. In this stage, a series of excellent frameworks, such as angular 1 and ionic, as well as module standards and loading tools such as AMD, CMD, UMD and requirejs, seajs, etc., have been produced. The front-end engineers have also become the specialized development field, with a technical system and architecture mode independent of the back-end. In the past two years, with the improvement of the complexity of web applications, the expansion of team members, and the needs of users for friendly interaction and performance optimization, we need more excellent and flexible development framework to help us better complete the front-end development. In this stage, many frameworks with relatively concentrated concerns and better design concepts have emerged, such as react, vuejs, angular 2 and other component frameworks, which allow us to replace the command-based programming with DOM operation as the core with declarative programming, which accelerates the development speed of components and enhances the reusability and composability of components. Redux, which follows functional programming, and mobx, which draws lessons from the concept of responsive programming, are very good state management auxiliary frameworks, which help developers separate business logic from view rendering, divide project structure more reasonably, implement single responsibility principle and improve code maintainability. In terms of project construction tools, the task operation management represented by grunt and gulp and the project packaging tools represented by webpack, rollup and JSPM are in the leading position. They can help developers better build the front-end construction process, and automatically perform preprocessing, asynchronous loading, Polyfill, compression and other operations. The dependency management tools represented by NPM / yarn have always ensured the convenience of code release and sharing, and laid an important foundation for the prosperity of the front-end community.

Rainbow of troubles

I saw it two days agoThomas FuchsWe spent 15 years to split HTML, JS and CSS, but overnight, the transaction seemed to be back to the origin.
2016 - my way to the front end: instrumentalization and Engineering
No matter the division of each module in front-end development or the so-called separation of front-end and back-end can not be formally divided according to language or module, or need to take into account the function and reasonable division. The author is in2015 my way to the front end: data flow driven interfaceAs mentioned in his 2015 front-end experience summary, any programming ecology will go through three stages. The first is the primitive period, which will spawn a large number of tools due to the need to expand the language and basic API. In the second stage, with the complexity of things to be done, more organizations are needed. A large number of design patterns and the concept of architecture patterns will be introduced. This stage will generate a large number of frameworks. In the third stage, with the further complexity of the requirements and the expansion of the team, it has entered the engineering stage, including various hierarchical MVC, MVP, MVVM, visual development, automated testing, team collaboration system. There will be a large number of small and beautiful libraries at this stage. In the first half of 2016, the author struggled with the technology stack of react, and tried other excellent front-end frameworks such as vuejs and angular. In this process, the author is very tired from the command development mode which directly operates DOM nodes to the development mode centered on state / data flow. In the second half of 2016, the author constantly reflected whether it was necessary to use react / Redux / webpack / vuejs / angular, and whether it was necessary to constantly pursue various new frameworks to refresh benchmark records? This paper is named tool oriented and engineering oriented, which represents the main purpose of this paper. I hope to get rid of the constraints of tools as far as possible, return to the front-end engineering itself, and return to the language itself. No matter react, angularjs, vuejs, their more significance is to assist development, select appropriate tools for different projects, rather than focus on the tool itself.

In conclusion, the current front-end tool has entered a very prosperous era, followed by many front-end developers are also very distressed, tired of learning. The change of tools will be very rapid. Many excellent tools may be just a spray in the long history, and the engineering thinking contained in them will last forever. Whether you are using react or Vue or angular 2 or other excellent frameworks should not hinder us from understanding and trying others. In the process of learning Vue, I feel that I have deepened my understanding of react, deepened my understanding of modern web framework design ideas, and broadened my vision for myself to choose scaffolding flexibly and flexibly according to local conditions in future work.

At the end of the introduction, I’d like to mention one word, which is the most popular word I’ve seen in the front end this year: tradeoff.

Instrumentalization

2016 - my way to the front end: instrumentalization and Engineering

It is better to have a surplus than to lose. I believe many people have seen itWhat is the experience of being a front end in 2016This article, 2016 front end really let people feel from the beginning to give up, we have not been able to follow the speed of new framework new concepts emerging, the cost of learning is far greater than the actual development project cost. However, the author is very welcome to the instrumented wave. We don’t have to use the latest and best tools, but we have more options, and I believe this is a good news for most non Virgo people. There is another one at the end of the yearCao Liuyang: front end technology observation in 2016It also caused a heated discussion. To be honest, I personally agree with the views in the article by half to half, and I don’t want to blow or black. However, the first feeling of this article is that the author must have come from a large company. Many of the features mentioned in this paper are the consideration of technology selection caused by technical liabilities and the ability to have relatively complete human resources to carry out a project, which are often not possessed by small and medium-sized enterprises.

The significance of instrumentalization

Instrumentalization makes sense. I agree with you hereYouyuxi: Vue 2.0, progressive front end solutionThe existence of tools is to help us deal with the complexity. In the process of technology selection, the abstract problem we are facing is the comparison between the complexity of the application and the complexity of the tools used. The complexity of a tool can be understood as an investment in dealing with the inherent complexity of a problem. Why investment? That’s because if you invest too little, there will be no scale effect and there will be no reasonable return. It’s like starting a venture capital company. How much is an important issue. If the problem to be solved is very complex, then if you deal with it with a too simple tool, you will encounter the problem that the tool is too weak to affect productivity. On the contrary, if the problem to be solved is not complex, but you use a very complex framework, it is equivalent to killing chickens with a knife. You will encounter the side effects brought by the complexity of the tool. You will not only lose the advantages brought by the tool itself, but also increase various problems, such as training costs, first-hand costs, and actual development efficiency.

2016 - my way to the front end: instrumentalization and Engineering

The author is inTen years of changes in GUI application architecture: MVC, MVP, MVVM, unidirective, cleanThe so-called GUI application architecture is the code organization / responsibility division for rich clients. Looking at the changes of architecture patterns in the past decade, we can roughly divide them into three categoriesMV*While clean architecture has its own way with strict hierarchical division. From the author’s cognition, the transition from MVC to MVP completes the decoupling of view and model, and improves the responsibility allocation and testability. From MVP to MVVM, the data binding between view and ViewModel is added to make the view completely stateless. Finally, the whole transition from MV * to unidirectional is to adopt a message queuing data flow driven architecture, and the solution represented by Redux willMV*The fragmented state management is changed into unified state management, which ensures the order and traceability of the state. In the evolution of the front-end, in the era of the rise of angular 1, it has actually begun to change from directly operating DOM nodes to focusing on state / data flow. JQuery represents the traditional DOM centered development mode, but the data / state centered development mode represented by react is popular in complex page development. After the application is complex, operating DOM directly means maintaining the state manually. When the state is complex, it becomes uncontrollable. React takes the state as the center, which can automatically render DOM for us. At the same time, through the efficient DOM diff algorithm, it can also guarantee the performance.

Deficiency of instrumentalization: Abstract vulnerability theorem

Abstract vulnerability theorem was proposed by Joel in 2002. All self-evident abstractions have vulnerabilities. Abstract leakage refers to any abstraction that tries to reduce or hide the complexity. In fact, it can not completely shield the details, and the complex details that are trying to be hidden will always leak out. Abstract loophole rule shows that: at any time, an abstract tool that can improve efficiency can save our working time, but it can’t save our study time. We discussed in the last chapter that the introduction of instrumentalization actually eliminates the inherent complexity at the cost of bearing the tool complexity, and the result of instrumentalization abuse is thatImbalance between instrumental complexity and intrinsic complexity

When we talk about this, we will understand that different projects have different internal complexity. It is just a rogue to comment on the quality and applicability of tools in a one-size-a-kind way. Moreover, we can not ignore the impact of the quality of project developers, customers or product managers on the internal complexity of projects. For typical small activity pages, such as a wechat H5 propaganda page, they often focus on interactive animation and loading speed, and the logic complexity is relatively low. At this time, Vue, which is a progressive library with low complexity, will be able to play its role. For complex web applications, especially those that need to consider multi terminal adaptation, the author tends to use a relatively strict library such as react.

React?Vue?Angular 2?

2016 - my way to the front end: instrumentalization and Engineering

Recently, the author has translated several review articles and found that it is very interesting. If the article does not mention or praise Vue, then a stream of comments: junk articles; if the article does not mention or praise angular 2, then a line of comments: junk articles. It is estimated that if the author did not even mention react, it would be a stream of comments: junk articles. Well, although it may be that the author’s translation is indeed not good, which tarnishes the original text, but this kind of anger is actually a disrespect for technology. React, Vue and angular 2 are very excellent libraries and frameworks. They have their own advantages in different application scenarios. This chapter is a brief description of the author’s point of view. The biggest advantage of Vue lies in its progressive thinking and more friendly learning curve. The biggest advantage of angle 2 is that it forms a complete all in one framework out of the box. In some cases, these two advantages are also its disadvantages and the reason why some people choose react. The author thinks that a lot of disputes about technology selection and even abuse are not necessarily the problems of tools, but that the users of tools can not correctly understand themselves or transpose themselves to think about the application scenarios of others, and finally the quarrel is not the same.

Small and beautiful view layer

React and vuejs are so-called small and beautiful view layer libraries, rather than the inclusive frameworks like angular 2. Any programming ecology will go through three stages. The first is the primitive period. Due to the need to expand the language and basic API, this stage will produce a large number of tools. In the second stage, with the complexity of things to be done, more organizations are needed. A large number of design patterns and the concept of architecture patterns will be introduced. This stage will generate a large number of frameworks. In the third stage, with the further complexity of the requirements and the expansion of the team, it has entered the engineering stage, including various hierarchical MVC, MVP, MVVM, visual development, automated testing, team collaboration system. There will be a large number of small and beautiful libraries at this stage.
Instead of providing a lot of complex concepts and tedious APIs, react focuses on providing clear, concise and abstract view layer solutions with the goal of minimization. At the same time, it provides flexible extension solutions for complex application scenarios. For example, state management tools such as mobx / Redux are introduced according to different application requirements. React is better than others in ensuring good expansibility, completeness of basic knowledge required for advanced research and learning, and testability of the whole application layer. However, many people’s opinions on react lie in its steep learning curve and high starting threshold. Especially with the introduction of JSX and a large number of ES6 syntax, many front-end developers who are accustomed to jQuery syntax feel that the learning cost may be greater than the development cost. In contrast, Vue is a typical so-called progressive library, which can introduce various dependencies and learn relevant grammar knowledge on demand. The intuitive feeling is that we can download Vue library directly from CDN at the beginning of the project, insert it into HTML with familiar script method, and then directly use Vue in script tag to render data. As time goes on and the complexity of the project increases, we can gradually introduce routing, state management, HTTP request abstraction, and finally the overall packaging tool. This progressive feature allows us to freely match different solutions according to the complexity of the project. For example, in a typical active page, Vue can have the advantages of both development speed and high performance. However, this kind of freedom also has advantages and disadvantages. The so-called “sharpening the knife does not make mistakes in cutting wood workers”, and the relatively strict specification of react will add a good bonus to the unity of code style and style within the team, and code quality assurance.
In a word, the author personally thinks that Vue will be more easily accepted by pure front-end developers. After all, the cost of Vue switching from direct HTML layout and jQuery data operation to directive support of bidirectional data binding will be a little lower, especially for the existing code base transformation needs less, and the reconstruction cost is lower. However, react and its relatively strict specifications may be more easily accepted by developers transferred from the back-end, and they may be confused by a lot of concepts at the beginning of learning. However, after being proficient, this rigorous operation of component classes and member variables / methods will be more convenient. In order to ensure the continuity of the products, the aim of danramov is to ensure the continuity of the products.

Functional thinking: abstract and intuitive

In recent years, with the increasing complexity of application business logic and the large-scale application of concurrent programming, functional programming has been brilliant in both front and back end. There is a famous saying in the field of software development: variable state is the source of all evils. Functional programming is to avoid using shared state and avoid some common pain points in object-oriented programming. However, to be honest, the author does not want to blindly advocate functional programming. In the following discussion on Redux and mobx, the author will also mention that functional programming will inevitably make the business logic fragmented, but will reduce the maintainability and development efficiency of the whole code. Compared with react, Vue is a very intuitive code architecture. Each Vue component contains a script tag. Here we can explicitly declare dependencies, declare methods to manipulate data, and define properties inherited from other components. Each component also contains a template tag, which is equivalent to the render function in react, and can bind data directly by attributes. Finally, each component also contains a style tag to ensure that component styles can be isolated directly. We can take a look at a typical Vue component first, which is very intuitive and easy to understand, and the comparison between the two is helpful to understand the design idea of react.

<script>
export default {
  components: {},
  data() {
    return {
      notes: [],
    };
  },
  created() {
    this.fetchNotes();
  },
  methods: {
    addNote(title, body, createdAt, flagged) {
     return database('notes').insert({ title, body, created_at: createdAt, flagged });
  },
};
</script>
<template>
  <div class="app">
    <header-menu
      :addNote='addNote'
      >
  </div>
</template>
<style scoped>
  .app {
    width: 100%;
    height: 100%;
    postion: relative;
  }
</style>

When we turn the perspective back to react, the components as one-way data binding can be abstracted as the following rendering functions:

View = f(Data)

This abstract way of user interface really makes the author refreshing, so we can abstract the combination of interfaces as the combination of functions, and a complex interface can be deconstructed into the combination and transformation of several different function calls. In version 0.14, react gave up mixin function and recommended to use higher-order function pattern for component composition. A big consideration here is that mixin belongs to object-oriented programming, which is an implementation of multiple inheritance, while composition in functional programming can play the same role and ensure the purity of components without side effects.

Many people feel that JSX syntax looks very strange when they first learn react. Is this deviation from the traditional HTML template development method really reliable? (Vue also introduced JSX syntax support in version 2.0). We can’t simply compare JSX with traditional HTML templates. JSX is essentially aboutReact.createElement The main function of this function is to map the object in plain JavaScript to a DOM representation. The general idea is as follows:
2016 - my way to the front end: instrumentalization and Engineering

In modern browsers, the computing speed of JavaScript is much faster than that of DOM, especially when it comes to redrawing and re rendering. In addition, JavaScript objects are used to replace DOM, which is strongly related to the platform, which also ensures multi platform support. For example, with the help of reactnative, we can easily run a set of code on IOS, Android and other platforms. In conclusion, JSX is still JavaScript in essence, so we can retain the advantages of JavaScript functions in composition, syntax checking and debugging, and at the same time, we can get the convenience and better readability of declarative usage similar to HTML.

Front end separation and full stack: technology and people

2016 - my way to the front end: instrumentalization and Engineering

Separation of front and back end and whole stack are not new terms, which have led to a period of fashion. Five years ago, when I first came into contact with the idea of separation of front and rear end and the definition of full stack engineer, I felt very excited. At that time, I also wanted to be an excellent full stack engineer. But now I think that at that time, I was more in order to understand everything, but I was not proficient. When I encountered a little deeper problems, I was at a loss Comfort yourself. The separation of front end and back end of web has significant advantages, which plays an important role in the development speed and reliability of the whole product. The full stack engineer is of great significance to the programmer’s own improvement, and has a certain growth rate for the initial speed of the project. If the division is reasonable, it can promote the overall development speed and reliability of the whole project, but if the division is not reasonable, it will only lead to confusion of project interface. However, the two concepts seem to be in conflict. The separation of front and rear ends as we often say includes the following two aspects:

  • The server is responsible for the data rendering work by the front-end, and it is stipulated that the communication between the front-end and the server can only be through the standardized protocol.

  • The separation of organizational structure, from the early service developers to write an interface, into a complete front-end team to build an engineering front-end architecture.

The separation of front-end and back-end is essentially the application of different technology selection and project architecture for the front-end and the back-end, but many ideas of the two can also be integrated. For example, the ideas of responsive programming and functional programming are embodied in the front and back-end. However, the whole stack seems to have returned to the state of dividing according to the requirements, no matter from the division of technology or organizational structure. However, we must face the reality that a large number of engineers do not have the ability to achieve the full stack. This is not due to the specific code technology, but to the understanding of the front and rear end, as well as the understanding of the system business logic. If we assign a complete business block, at the same time, we end up with countless fragmented and independent systems.

Complementary client-side rendering and server-side rendering

The author is in2015 – my way to the front endIt is mentioned that the original web page is a mixture of data, templates and styles, that is, classic web pages APS.NET PHP and JSP, for example, provide a series of tags by the server-side template to complete the flow from business logic code to page. Therefore, the front end is only used to display data, so-called vassal. With the popularity of Ajax technology, webapp is also regarded as CS architecture. Abstractly speaking, CS is regarded as the two-way communication between client and server, while BS is one-way communication between client and server. In other words, the web itself has become stateful. From the initial opening to the final closing of the web page, the web page itself also has its own state, and the basis of this change is Ajax, that is, from one-way communication to two-way communication. The figure is as follows:

2016 - my way to the front end: instrumentalization and Engineering

The concept of server-side rendering has come back to people’s attention with the popularity of react in the past two years. It should be emphasized that the technology we now call server-side rendering is not the traditional server-side template data filling represented by JSP and PHP. A more accurate description of the role of server-side rendering is to pre start and preload client-side applications. We try our best to pull the client code back to the server to run, not to replace the existing API server, and the code that has run in the server also needs to be re run on the client. Here, we recommend to refer to the author’sWebpack2-React-Redux-BoilerplateThe migration path from pure client rendering to server rendering is described step by step in three levels. The advantages of introducing server-side rendering mainly lie in the following three aspects:

  • For the improvement of browser compatibility, at present, react, angular, Vue and other modern web frameworks have given up support for the old version of the browser. After the introduction of server-side rendering, at least for users using the old version of browser, it can provide a more friendly first screen display, although the subsequent functions still can not be used.

  • More search engine friendly, client rendering means that the overall rendering is done by script, which is not friendly to crawlers. Although modern crawlers often support script execution through built-in automated browsers, this will virtually increase the load of many crawler servers. Therefore, large search engines like Google still rely on documents when indexing web pages. If you want to improve your ranking on search engines and make it easier for your website to be searched, then supporting server-side rendering is a good choice.

  • Overall loading speed and user experience optimization, in the first screen rendering, the performance of server-side rendering is much faster than that of client-side rendering. However, in the subsequent page response update and sub view rendering, due to the scope of network bandwidth and re rendering, the server-side rendering is weaker than the client-side rendering. In addition, while rendering on the server side, we will also grab part of the application data on the server side and attach it to the document. Under the current situation that http / 1.1 is still the mainstream, it can reduce the number of connection requests and delay of the client, and let users access the required application data more quickly.

In conclusion, server-side rendering and client-side rendering are complementary. With the help of react and other frameworks, we can easily add server-side rendering support for pure client-side rendering applications in the development stage.

Full stack engineer in project: full stack of technology, requirement isolation and reasonable allocation

Full stack engineers are of great significance for personal development, especially for small and medium-sized start-up companies, which take progress as the first baton. But the whole stack often means a certain tradeoff. If the steps are too big, it is easy to pull eggs. Any technical structure and process adjustment should not violate Conway’s law, that is, the design of the organization that designs the system is equivalent to the communication structure within and between organizations. This is the first time that the author mentioned Conway’s law in this paper. In practice, the author found that some of the results of the whole stack are forced to allocate tasks according to functions. In other words, it is possible to allocate the whole part of login and registration from database design, server-side interface to front-end interface for one person or a group. In order to normalize the interface, the executor should ignore all aspects of the specification. Finally, the whole system is fragmented into islands one by one, and the names of variables with the same meaning between different function blocks can conflict, and all kinds of strange ID, UUID, and {resource} can conflict_ ID is dazzling.

At the end of this year, a lot of technical exchange platforms raised a complaint against the full stack of engineersWhy does the whole stack engineer recruit blackmailAs an example of this discussion, the black spots of all stack engineers are as follows:

  • Leon ready: it’s more and more difficult for a full stack engineer to exist. Many people just make up for the number. With the development of the Internet, in order to cope with different challenges, different directions need to spend a lot of time and energy to solve problems, so job segmentation is inevitable. Over the years, the accumulation of expert experience and skills in each direction is not in vain. People’s energy and time are limited. The later the development, the less chance the whole stack will appear.

  • Wheel brother: a person can pursue the whole stack, that is his personal freedom. But if a job pursues the whole stack and then advocates such things, it proves that the company is unhealthy and inefficient.

An important feature of modern economic development is that social division of labor is increasingly refined and clear. It is only Nanke’s dream to become an omniscient generalist. However, in the above criticism, we can also see that the whole stack of engineers is of great significance to the development of individuals. They can only draw inferences from one instance only when they can learn from each other. The author advocates job rotation in his own small team. Generally, after the completion of a project cycle, the positions of some front-end and rear-end engineers will be changed. On the one hand, it is to avoid complicated transactional development that makes everyone too tired. On the other hand, I hope everyone understands each other’s work, so that when a bug occurs, they can think in a different position. After all, the contradictions within the team, especially the contradictions between the various groups, have always been a headache in project management.

2016 - my way to the front end: instrumentalization and Engineering

Engineering

This part should be the most important chapter, but if you don’t write the graduation thesis, you will be killed. T, t, the author will supplement and improve it in the future.

2016 - my way to the front end: instrumentalization and Engineering

What is engineering

The so-called engineering refers to the technical architecture and project organization oriented to the requirements of a product. The fundamental goal of engineering is to achieve reliable products as quickly as possible. The shortest possible time includes the development speed, deployment speed and reconfiguration speed, and the reliability lies in the testability and variability of products, as well as the recurrence and positioning of bugs.

  • Development speed: development speed is the most intuitive and obvious engineering measurement index, and also the core contradiction between other departments and programmers and programmers. Most of the excellent engineering solutions first solve the problem of development speed. However, the author will always emphasize that when we pursue the fastest local speed, we should not neglect the overall optimization. The technical debt caused by the simple pursuit of speed in the initial stage will cause irreparable damage to the later stage.

  • Deployment speed: in my daily work, the longest thing I say to the test or product manager is that I have improved it locally and haven’t been pushed to the online test environment. With the concept of Devops deeply rooted in the hearts of the people and various CI tools are popular today, automatic compilation and deployment can save us a lot of trouble. However, the deployment speed is still an important indicator that can not be ignored, especially the elusive package management tools represented by NPM and servers that do not know when the wind will blow up will pose a great threat to our compilation and deployment process. The increase in the number of project dependencies and the confusion of structure division will also increase the uncontrollability of deployment speed.

  • Reconstruction speed: according to the product manager, our requirements will change again. According to the technology leader, a new technology stack has been created recently, which has dropped to the current level.

  • Testability: many teams now advocate test driven development, which is of great significance to improve the quality of code. The project options will also have a great impact on the testability of the code. There may be no code that cannot be tested, but we should try our best to reduce the cost of testing code and encourage programmers to write test code more actively.

  • Changeability: programmer says: this demand cannot change!

  • Recurrence and positioning of bugs: there is no program without bugs, especially in the case of unclear initial requirements, the emergence of bugs is inevitable and inevitable. Excellent engineering solutions should consider how to help programmers locate bugs more quickly.

Whether it is the separation of the front and rear end, or the popular microservice in the back end or the microfrontend in the front end, the core is to sacrifice the local development speed for faster global development speed and the improvement of the system’s reliability. The difference between junior programmers and intermediate programmers may be that the former can only realize, but only know it, but they don’t know why. Their only measure is the development speed, that is, the speed of function realization or the amount of code, etc. Intermediate programmers can take into account the development speed and quality of the code within their scope of responsibility. They will continue to merge and split through continuous review in the development process, so as to achieve as little code as possible on the basis of adhering to the SRP principle. On the other hand, the difference between coder and Teamleader is that the former pays more attention to local optimization, which may refer to a specific module in the front and back end of the project, or the latest development goal in the time dimension. The team leader needs to plan strategies and plan the overall situation. It is not only necessary to complete the tasks delivered by the boss, but also to reserve interfaces for possible modification and iteration of products or lay a foundation for scalability in advance. In conclusion, when we explore the specific implementation scheme of engineering, in terms of technical architecture, we will focus on:

  • Modularization of function and Componentization of interface

  • The unified development specification and code style can achieve the required functions with the least code under the premise of following the single responsibility principle of SRP, that is to ensure reasonable separation of concerns.

  • Testability of code

  • Code base and dependency management tool for easy sharing

  • Continuous integration and deployment

  • Online quality assurance of project

Engineering requirements of front end

When we landed at the front end, the author felt the following outstanding problems in the practice over the years:

  • Front end and back end business logic Convergence: in the case of separation of the front and rear end, the front and back end are the system and team, so the communication between the front and back end has become one of the main contradictions in the project development. When the front-end is developing, it often divides the modules and names the variables according to the interface, while the back-end is used to dividing the modules according to the abstract business logic and naming the variables according to the database definition. The simplest but most common problem is that the two may have different names for variables with the same meaning, and considering the frequent changes of business requirements, the background interface will also change frequently. At this time, it is necessary for the front-end to establish a special interface layer to shield this change and ensure the stability of the interface layer.

  • Component reuse of multiple business systems: when we are faced with new development requirements or have multiple business systems, we hope to reuse the existing code as much as possible, not only to improve the development efficiency, but also to ensure the consistency of application style within the company.

  • Multi platform adaptation and code reuse: in the face of the mobile wave, our application needs to consider not only the support of PC, but also the support of wechat applet, H5, WAP, reactnative, weex, Cordova and other platforms. Here, we hope to reuse the code as much as possible to ensure the development speed and reconstruction speed. What needs to be emphasized here is that the mobile terminal and the PC terminal are different design styles. The author does not agree with excessive consideration of the so-called responsive development to reuse interface components, and more attention should be paid to the reuse of logical code, although this will inevitably affect efficiency. You can’t have both. This needs to be adapted to local conditions, and it can’t be generalized.

To sum up the specific technical points, we can draw the following evolution chart:
2016 - my way to the front end: instrumentalization and Engineering

Declarative rendering or variable imperative operation is needed in any case. From DOM operation as the core to data flow driven, it can reduce redundant code and improve development efficiency. I still want to take the comparison between jQuery and angular 1 as an example

var options = $("#options");
$.each(result, function() {
    options.append($("<option />").val(this.id).text(this.name));
});
<div ng-repeat="item in items" ng-click="select(item)">{{item.name}}
</div>

At present, react, Vue, angular 2 or its extensions provide support for declarative components based on ES6. Then, on top of the basic declarative components, we need to build reusable and composable component systems. Often, a component system is composed of nullable units segmented from a large interface of an application, which is the deconstruction design draft in the front-end architecture below. When we have a large component system, or many components, we need to consider the jump between components. Especially for single page applications, we need to map the URL to the application state, and the application state determines the currently displayed components. At this time, our application is becoming more and more complex. When the application is simple, a very basic state and interface mapping can solve the problem. However, when the application becomes large and involves multiple people’s cooperation, it will involve the sharing of multiple components, multiple components need to change the same state, and how to make such large-scale applications still run efficiently When it comes to large-scale state management, it’s also about maintainability and build tools. Now, if you look at the future of the front end, when http2 becomes popular, it may lead to a revolution in building tools. But at present, especially in China’s network environment, packaging and engineering construction is still a very important and inevitable link.
Finally, from the front-end project category, it can be divided into the following categories:

  • Large web application: the business function is extremely complex. After using the MVVM framework such as Vue, react, angular, in the development process, there will be more and more components, and the communication frequency between parent and child components and between child components will be greatly increased. How to manage the data flow between these components will become the biggest difficulty of this kind of webapp.

  • Hybrid web app: the contradiction lies in performance and user authentication.

  • Activity page

  • game

Microfrontend: Micro front end

MicroservicesThere is no doubt that the convenience of building a scalable and maintainable large-scale service cluster has been brought, and now with the increasing complexity of front-end applications, the so-called megalithic front-end applications are emerging in endlessly. As with server applications, large and bulky web applications are also difficult to maintain. Therefore, ThoughtWorks proposed the concept of micro front end this year. The core idea of micro front-end and micro service are the same. Giant web applications are segmented according to the page and function. Different teams are responsible for different parts. Each team can apply relevant technologies to develop relevant parts according to their own technical preferencesBFF – backend for frontendsIt will come in handy.

Front end development plan returning to reality

The last part of this paper focuses on the front-end development plan of the author in one year’s practice. It is estimated that this paper is just a brief introduction. There will be a special article for detailed introduction in the future. Why is it called the back to reality front-end development plan? Because I feel that the biggest problem is that the requirements are not clear, the interface is unstable and the quality of developers is uneven. First of all, regardless of the technical level, we hope at the organizational level in the project development so that everyone involved can maximize its value regardless of their level. Everyone can write components and entity classes, but they may not be able to write appropriate high-quality code. On the other hand, good architectures are all derived from different industries, application scenarios and interface interaction requirements. We need to keep an open mind and constantly extract public code to ensure the appropriate degree of reuse. At the same time, we should avoid a series of problems caused by excessive abstraction. The reasonable team matching method advocated by the author is as follows: This is more oriented to small companies with insufficient staff. One is for two purposes, and I wish everyone was in the whole stack
2016 - my way to the front end: instrumentalization and Engineering

Declarative programming and data flow driven: gains and losses

Redux is completeThe idea of functional programmingPractitioners (if you don’t understand Redux enough, you can refer to the writer’sIn depth understanding Redux:10 Redux practice suggestions from experts)Its core technology is based on the reducer that follows the pure function and the single state tree that follows the immutable object. It provides extreme predictability and extreme testability, which requires a lot of boilerplate. andMobXThe core idea is anything that can be derived from the application state, should be derived. Automatically. Redux uses the uniform single state tree, and is used to object oriented in the back-end development The author of programming also wants to introduce entity in the front end, or in terms of design ideas, such as adding, deleting, modifying and querying todolist, the author hopes to be included in a todolist object, instead of dividing all operations into three parts: Creator, reducer and selector. I just want to show a list simply. The first class of the author’s University study is about OOP, including the practice in many back-end fields such as C ා, Java, python, PHP and so on, they are deeply influenced and instilled with OOP ideas. It is undeniable that the changeable state is the root of all evils in software engineering. However, the description of business logic and the guarantee of readability and comprehensibility of code organization in OOP are better than those of declarative, slightly Abstract FP. I agree that the idea of functional programming is an integral part of the project building organization, but should the idea of programming be discussed first and then the business requirements at any stage of any project? It’s a bit of a politically correct rascal. Typical situations recommended by Dan for Redux are as follows:

Progressive state management

Do different things in different time periods. When we are writing pure components, we need to explicitly declare all state / data, and for actions, we can put them into the store to postpone operations. Take a simple form as an example. At the beginning, we will encapsulate all the logic of form data input, validation, submission and result feedback in form components. Then, with the increasing complexity of components, we need to segment the code for different functions. At this time, we can establish a special store to handle the state and logic of the form. Abstractly speaking, the state management we need in different stages corresponds to:

  • Prototype: local state

In this stage, we may directly put the data acquisition function into componentdidmount, and store the UI state and domain state in the localstate by using the setstate function. The development efficiency of this method is the highest, after all, the amount of code is the least, but its scalability is slightly poor, and it is not conducive to sharing state between views.

// component
<button onClick={() => store.users.push(user)} />

Here, store only refers to pure data storage or model class.

  • Project growth: external state

With the complexity of the project, we need to find a special state management tool to manage the external state

// component
<button onClick={() => store.addUser(user)} />

// store
@action addUser = (user) => {
  this.users.push(user);
}

At this time, you can also modify the state directly within the component, that is, use the code style of the first phase and directly operate the store object. However, you can also avoid this bad practice by introducing the strict mode

// root file
import { useStrict } from 'mobx';

useStrict(true);
  • Multi person collaboration / strict specification / complex interaction: Redux

With the further increase of project volume and the increase of participants, it is the best practice to use declarative actions and it should be the time for Redux to shine on the stage. At this time, Redux has the biggest limitation, and it can only change the application state directly through action.

// reducer
(state, action) => newState

Progressive front end architecture

The front-end architecture in my mind is as follows, which is described according to the process of the project and the modules that should be developed at different development time

2016 - my way to the front end: instrumentalization and Engineering

Deconstruction design draft

2016 - my way to the front end: instrumentalization and Engineering

Pure components

After deconstructing the design draft, we need to summarize the pure components. At this time, the so-called storybook driven development is put into use, for example, the author summarizes itMaterial UI ExtensionThis generic class library.

Entity class

The entity class is actually a static type language. From the engineering sense, it can unify the data specification. The author mentioned Conway’s law, which designs the organization of the system, and the design generated by it is equivalent to the communication structure within and between organizations. Entity classes, supplemented by static type checking tools such as typescript and flow, can not only facilitate ide to prompt syntax, but also avoid static syntax errors as much as possible. At the same time, when the business requirements change, we need to reorganize part of the business logic. For example, when modifying some key variable names, we can modify them more conveniently and safely through the unified entity class. At the same time, we also need to put some logic into the entity class, such as the mapping between the state code and its description text, and the calculation of some static variable values

//Part associated drawing information
  models: [ModelEntity] = [];

  cover: string = '';

  /**
   *@ function according to the derived part cover address
   */
  get cover() {

    //Determine whether there is drawing information
    if (this.models && this.models.length > 0 && this.models[0].image) {
      return this.models[0].image;
    }

    return 'https://coding.net/u/hoteam/p/Cache/git/raw/master/2016/10/3/demo.png';

  }

At the same time, we can also define some common methods in the entity base class

/**
 *@ function the base class of all entity classes, named entitybase, in case of duplicate name with entity in DOM core
 */
export default class EntityBase {

  //Entity class name
  name: string = 'defaultName';

  //Default constructor that adds data to the current class
  constructor(data, self) {

    //Determine whether self is passed in. If it is empty, it will default to the current value
    self = self || this;

  }
  
  //Filter properties with a value of null undefined ''
  filtration() {
    const newObj = {};
    for (let key in this) {
      if (this.hasOwnProperty(key) && this[key] !== null && this[key] !== void 0 && this[key] !== '') {
        newObj[key] = this[key];
      }
    }
    return newObj;
   }

  /**
   *The @ function simply copies in the properties declared to exist in the class
   * @param data
   */
  assignProperties(data = {}) {

    let properties = Object.keys(this);

    for (let key in data) {

      if (properties.indexOf(key) > -1) {
        this[[key]] = data[[key]];
      }

    }

  }

  /**
   *@ function unified processing time and date objects
   * @param data
   */
  parseDateProperty(data) {

    if (!data) {
      return
    }

    //Unified processing created_ at、updated_ At
    if (data.created_at) {
      if (data.created_at.date) {
        data.created_at.date = parseStringToDate(data.created_at.date);
      } else {
        data.created_at = parseStringToDate(data.created_at);
      }
    }

    if (data.updated_at) {
      if (data.updated_at.date) {
        data.updated_at.date = parseStringToDate(data.updated_at.date)
      } else {
        data.updated_at = parseStringToDate(data.updated_at);
      }
    }

    if (data.completed_at) {
      if (data.completed_at.date) {
        data.completed_at.date = parseStringToDate(data.completed_at.date);
      } else {
        data.completed_at = parseStringToDate(data.completed_at);
      }
    }

    if (data.expiration_at) {
      if (data.expiration_at.date) {
        data.expiration_at.date = parseStringToDate(data.expiration_at.date);
      } else {
        data.expiration_at = parseStringToDate(data.expiration_at);
      }
    }

  }

  /**
   *@ function outputs the class as a JSON string
   */
  toString() {
    return JSON.stringify(Object.keys(this));
  }

  /**
   *@ function generates random numbers
   * @return {string}
   * @private
   */
  _randomNumber() {

    let result = '';
    for (let i = 0; i < 6; i++) {
      result += Math.floor(Math.random() * 10);
    }
    return result;
  }

}

Interface

The interface is mainly responsible for data acquisition. At the same time, the interface layer also has a responsibility to shield the interface details of the server side to the upper layer, and to assemble and merge the interface. The author mainly uses the summaryFluent FetcherFor example, we need to define the most common login interface:

/**
     *Log in via email or phone number
     *@ param account email or mobile number
     *@ param password password
     * @returns {UserEntity}
     */
    async loginByAccount({account,password}){
        let result = await this.post('/login',{
            account,
            password
        });

        return {
            user: new UserEntity(result.user),
            token: result.token
        };
    }

It is recommended that after the interface is written, the developer can directly and simply test the following:

let accountAPI = new AccountAPI(testUserToken);

accountAPI.loginByAccount({account:'[email protected]',password:'1234567'}).then((data) => {
  console.log(data);
});

Use it directly herebabel-nodeRun it, and then write more complex specs by professional testers.

Container / advanced components

Containers are often used to connect state management with pure components. I like the livetemplating function of IDE. Typical container templates are as follows:

// @flow
import React, { Component, PropTypes } from 'react';
import { push } from 'react-router-redux';
import { connect } from 'react-redux';

/**
 *Component containername, used to display
 */
@connect(null, {
  pushState: push,
})
export default class ContainerName extends Component {

  static propTypes = {};

  static defaultProps = {};

  /**
   *@ function default constructor
   * @param props
   */
  constructor(props) {
    super(props);
  }

  /**
   *Callback of @ function component mount completion
   */
  componentDidMount() {

  }

  /**
   *@ function default render function
   */
  render() {

    return <section className="">

    </section>

  }

}

Server rendering and routing

Server rendering and routing can be referred toWebpack2-React-Redux-Boilerplate

Online quality assurance: the difficulty of the front end is not in the front end

The completion of front-end development does not mean that everything is well. The author wrote in a weekly newspaper that the so-called bugs at present often fall into the following three categories:
(1) At present, this kind of bug will be reduced in the early stage of the project. However, with the development of large-scale debugging, the number of careless bugs will be reduced.
(2) Bugs caused by changes in requirements: this type of bug is inevitable and generally controllable. However, this type of bug has little influence in the formal environment, and at most affects the programmer’s personal mood.
(3) Bug caused by interface change: this type of bug is inevitable and has high theoretical controllability. Among the bugs fixed last week, this type of bug accounts for the largest proportion. It is suggested that release or milestone should be divided according to the version when the back-end is released in the future. At the same time, a certain gray level substitution period should be set after the official launch, that is, to maintain dual version compatibility for at least a period of time.

Online quality assurance is often faced with many uncontrollable factors, such as the company’s e-mail service arrears resulting in the failure to send registered e-mailsfrontend-guardianWe hope to improve it in the next year

  • Real time feedback on product availability

  • If not available, inform maintenance personnel immediately

  • If not available, it can quickly assist in locating errors

Frontend Guardian hopes to be a real-time monitoring and regression testing tool as simple as possible. Large companies can build their own systems or expand based on excellent tools such as falcon. However, small companies, especially in the early stage of entrepreneurship, hope to complete online quality assurance at a lower cost.

Extended reading

Postscript

At the end of 2016, as in the past, many excellent summary and inventory articles have emerged. The author has been writing this article off and on for a long time. The company’s projects are in a hurry to go online, and the graduation thesis will be postponed if it is not written again. During this period of time, after reading many of your works, I feel that my pattern and vision are rather low. This is also what I have always mentioned in the article that my experience and feelings come from small and medium-sized innovation teams. I hope to have the opportunity to further expand my vision next year. If anyone reading this article has a good communication group recommendation, welcome to tell me by private message, three people line, there must be my teacher, I also hope to be able to contact some real gods.