In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what is the difference between junk code and high-quality code". In daily operation, I believe that many people have doubts about the difference between junk code and high-quality code. I have consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what is the difference between junk code and high-quality code". Next, please follow the editor to study!
Examples of refactoring in several business scenarios
Request order dependence
In this scenario, first of all, the complexity of the business determines the complexity of the code. First, let's take a look at a simple example that can occur at both the front end and node:
We have A, B, C, D four functions that request to get data (the function implements itself), C depends on the result of B, D depends on the result of ABC, and finally outputs the result of D.
Error exampl
Although this code is written like this on purpose, it has been seen in some beginners. This code can still give the correct results, but the writing is ugly, callback hell. If later people do not refactoring and have request dependencies, they have to continue to call back nesting. The performance is too poor to consider that An and B can actually be concurrent.
Here is an introduction to the original callback. In the middle, you can review the evolution of ES2015+, callback (async.js)-- > Promise-- > generator + co-- > async + await. In fact, we continue to simplify and enhance our ability to control asynchrony from the original syntax level.
The following is the ultimate solution that is provided directly to the current stage: based on Promise + async/await
Correct example
We reconsidered the above question and clarified the dependence of logical order. And use the latest grammar.
In the form of Promise.all combined with async/await, concurrent and serial are taken into account, and the writing method is simple, which achieves the fastest scheme under the requirements of the example. The problem of infinite nesting is solved. This is the optimization that follows the evolution of the language itself.
But it's more than that. We categorize the problems and extract the separate functions from the requests of BMague C that depend on the sequence. Let them deal with their own logic. We'll talk about this later.
Torturing if else
There may be some problems as follows
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Too much nesting
Logical processing redundancy
Not well programmed for defense (error handling
Let's go straight to a code example, which is a way to get the background color, but as the business changes, there are more and more sources of background color, which may be like this with the help of some business people:
Error exampl
I believe that it is extremely painful for you to read the above code, and it is almost impossible to know which branch you will eventually enter at a glance. So based on the following two principles
Reasonable extraction into a function
Error first return
There is a basic version of refactoring:
Correct example
You can see the whole logic, which has been recombed. It is divided into three functions, the sub-methods deal with the logic of the corresponding level respectively, and a main method is responsible for scheduling. The whole has become clear at a glance.
Of course, is there something wrong with this code after we have refactored based on the above principles? Of course there is. You can see that all three of our functions rely on global variables. The function itself is impure. If it is an overall problem, it is still not easy to troubleshoot.
We can change it to a pure function to make this code easy to understand and test.
Take the modification of a function as an example: we change the global variable into a parameter, just pass in the global variable when it is called, but in this way, we get a pure function.
Why is this point particularly emphasized here? in fact, one of the most basic problems in functional programming is pure functions. Only in this way can the input and output be observed, and an input must have an output. Only in this way can there be fewer and fewer impure functions in the system. Make the code easier to test.
Of course, if we think about it in terms of refactoring, we also need to pay attention to this point:
The logic here will set the last data to be matched to bgColor. We all know that find indexOf and so on are basically matching in the past.) Is it really the demand of the business?
You can see that the process of writing / refactoring business code is actually another improvement in business logic and business understanding. Whether it is extracted into a function or error-first return design, this can actually solve such a problem: to be able to understand the detailed logic of a certain area without understanding the overall situation, which makes the code easy to understand and modify.
... Even after such refactoring, the code here still has room to consider further optimization, such as the naming of functions and parameters, complete test cases and so on.
Other problems that may exist in some code
1. Logically coupled in the view layer.
A ='a'& & b ='b' & & croups.c` & d ='d'?: null
two。 Component reuse, function reuse, no encapsulation, code repetition.
3. The function is not single, one function handles too many responsibilities. And these responsibilities are not related, but they are all coupled in the same block.
4. Messy parameter list, defensive programming, no handling of errors (interface errors, timeouts, repeated commits, etc.)
5. Magic numbers, magic strings, and no description.
6. Bad data structure / bad naming (in fact, the specific code examples above also exist)
On the ideological preparation of optimizing Code
First of all, why do you say that you need to optimize the code?
Pursuit of technology.
The company requires that there is a system in use online. There are users in use, do not write a good problem is actually suffering from their own.
Teamwork, I do not write well, team members do not write well, the vicious circle is still their own.
Fast iteration. The system needs to add new functions constantly. You have to write good code to do that.
In the opinion of others, they are afraid that others will think that their technical ability is poor. Xxxx....
Then there will be the following requirements:
Easy to understand the architecture of the system
Easy to understand the life cycle and execution process of the system
It is easy to understand the role of each function.
It is easy to understand how functions are called and passed (input and output)
It is easy to understand the meaning of variables and expressions.
It is easy to expand.
In the end, it actually goes back to writing code that is supposed to be clean, making it easy to understand / modify / test. (in fact, most of the time, a condition for personnel collaboration is implied in it, so it is necessary to write good code without over-encapsulating it so that the rest of the team members cannot understand it (of course, if some people are not experienced enough, then it is his own problem, which needs to be strengthened by himself.)
Some suggestions
Understand the business more clearly and think about possible changes. Think and design clearly before you do it.
Look at some open source projects and industry best practices to understand what is good code and what is bad code.
Build to understand that although the code is for the computer to run, it is ultimately for people to read. It's not just a mental model without bug.
Establish a thinking model in which business is as important as code quality. Avoid code that has to be written this way because of time.
Understand that code review itself may be able to find and point out some problems, but the final implementation is still on their own, not into a form, but needs to be integrated into their own thinking.
Use the principle of error first. As much as possible, let the error return first, so that you will get clean code later. (when writing code, not only positive but also reverse judgment needs to be considered.)
Reasonably split into independent functions. Clear input and output, error handling and other processing within the function. (for example, in some scenarios, there is indeed a large number of logical judgments, the first thing to consider is whether the internal statements can be classified and separated.)
For the judgment and combination of multiple states, we can use modes such as combined state table (map table) state machine, etc.
Learn design patterns and refactoring and other related knowledge.
Refactoring! As long as you think there's something wrong with this place, don't wait until later. In the future, it is often never again.
At this point, the study on "what is the difference between junk code and high-quality code" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.