In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "how to write highly readable code". In the operation process of actual cases, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!
Know your priorities.
There are many ways to write code: some run fast, some take up a small amount of memory, some are easier to test, and some are highly readable.
The first step in writing clear-thinking code is to put readability first.
This also means that other factors must be given lower priority. If all factors are given the highest priority, it means that there is no priority.
Cultivate clear awareness
To write good code, you must first know what is good code, and to write clear code, you must also know what is clear thinking. Reading a lot of good code gives us an idea of what good code looks like.
Knowing what good code is doesn't stop us from writing bad code, but it does at least tell us what's wrong with it.
revised
When we write code, we don't always think clearly. In most cases, we can only find a better idea after we finish the code for the first time. Reading the completed code over and over again brings room for change.
Start with explanation.
If we still don't understand the structure of the code, imagine explaining it to others or writing down the logic, such as "If we delete accounts, we need to skip xxx. If the process of xxx is not finished, then..." Then translate this logic into code and it will be very smooth.
When writing programs, it is easier to bring in human communication rather than abstract concepts from computers.
annotation
Comments in the code can explain why a particular piece of code is useful, or why the program structure is written the way it is.
The reading program alone does not tell us that what the author thinks is the correct logic. There may be business rules we don't understand: users outside the u.s. sometimes write street names to the end of the first line of the address bar. There may also be some technical tricks involved: structuring the query in some strange way so that Postgres optimizes it correctly. Such code details can only be fully understood if you understand the background behind the logic.
Code doesn't speak. If we decide to skip certain steps, but don't bother to leave comments explaining why, then come back to this code in a couple of days and nobody really knows what you were thinking.
Part of the code may be read twice to figure out why, but to be on the safe side, don't put unnecessary burden on your brain.
Don't confuse the layers.
Don't confuse levels of abstraction in functions.
This "welcome" code is a mess:
def welcome(self): results = db.query( 'SELECT EXISTS 1 FROM emails WHERE kind = ? AND user = ? ', 'welcome_email', self.user.id, ) if results[0]: return self.send_welcome_email()
This is relatively neat:
def welcome(self): if not self.has_sent_welcome_email(): self.send_welcome_email()
The jumbled levels of abstraction in functions force readers to think outside the box when thinking about what the code does and how it is implemented. The code at the current level of abstraction tells us what the code is doing, and the code at the next level tells us how the code is going to be implemented.
In the example "welcome" function, we first query the database for past mail records, and if not send a welcome email. Note that the "welcome" function in the second version puts the query part into another function, and the "welcome" only focuses on "what to do." This keeps the abstraction level in the function at the same level, and the logic is clearer. Different functions are scattered at different levels of abstraction, delegating lower-level implementation details to functions at lower levels of abstraction.
decomposition function
Sometimes it's easier to read by breaking down a large volume function into subfunctions.
For a step-by-step function, it is better to break down each step in the function into subfunctions. For other functions, such as decision classes, different decisions lead to different functions: some are responsible for making decisions, while others are responsible for implementing decisions. There are many dimensions to the decomposition of functions, and it is only with practice that one can see at a glance which one is correct.
Small-volume functions have several advantages:
Each part of the logic has its own function name. It's easier to know what each piece of logic is responsible for and find out where these functions should be placed.
Fewer variables in scope
Better visibility of functions when running stack traces and debugging
Small functions can be tested separately
In fact, the computer can run well without any functions. Functions exist only to serve programmers, so please use them more.
Do not decompose functions
The meaning of don't repeat yourself (DRY) is often overinterpreted.
The extraction of magic constants and logical copies of certain types of decisions is now accepted as standard answers. Such repetitive code is bad. DRY's over-interpretation refers to the fact that in the face of a mere two lines of repeated code, it is as if an enemy wants to get rid of it quickly. Avoiding any duplication of code altogether means we end up with a bunch of meaningless, confusing code that exists only to prevent two or three lines of duplication in our programs. Add to that the fact that two logically unrelated pieces of code are forced to bind together, and the code is harder to modify.
Determining whether duplication is tolerated in a piece of code is simple: modify section A and leave section B unchanged. If the program reports an error, put A and B into the same piece of code; if nothing happens, leave it alone. DRY doesn't mean we need to compress the code base manually, but rather to avoid two pieces of code depending on manual synchronization. Remember, repeating code and abstract creation are not the same thing.
Avoid configurable functions
It is better to have a small function with ten zero arguments than a function with ten arguments.
You are no stranger to similar things: functions that are initially clean are called only in three different places. And when we want to call it in the fourth place, we need to make a small adjustment and add a parameter. But this first caller adds a new feature and two more configurable parameters. We wait until the fifth use case to add unique parameters to it, and so on. But then we find that the second caller runs too slowly, so we have to add another parameter to skip some of the tedious procedures.
Before you know it, our neat, one-thing function now has five configuration parameters and can do two to the fifth power of things!
In this case, it would be much better to break up the whole complex function into subfunctions, each responsible for its own thing.
However, since then, duplication is inevitable. When these repeated parts need to be synchronized, we can use DRY ideas to extract the same parts into subfunctions. At this point, making decisions and considering steps becomes much easier.
Remember, just a few lines of duplicate code is fine! For example, code that runs for loops on different lists is acceptable duplication.
One of the benefits of this approach is that when one of the use cases is deleted, you can easily delete the corresponding function instead of digging through the logic of complex functions to find the corresponding option. Readers who focus only on a particular function will also have an easier time understanding their usefulness.
(Note that this method is correct when you are responsible for all callers.) If your function is only part of a common API, then don't consider using this approach. Because you don't know what all the use cases are, and you don't know what the future holds.)
Don't optimize too early
There is no doubt that racing cars run faster than ordinary cars. But it's also a race car at the expense of soft seats, low noise and on-board air conditioning. If our program doesn't require racing, don't remove the air conditioner prematurely. Get familiar with the structure of the program, starting with code that is easy to understand, rather than trying to challenge the speed of the computer.
Similarly, generalization should not begin too early. No one buys a dump truck when they don't have to handle a lot of stuff, and we don't have to code extra features in advance when there's not too much demand.
"How to write high readable code" content is introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
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.