How to write good code

(This article is reproduced from another blogger but I have forgotten the source)

What is good code?

High-quality code refers to those that are easy to understand, easy to maintain, highly readable, clear in structure, without redundancy, high in operating efficiency, strong in reusability, and good in stability , highly scalable code.

This type of code not only accurately performs the intended function, but is also easier for other developers to understand and modify.

This type of code usually follows certain design patterns and programming specifications, has a clear logical structure and standardized code format, and has appropriate and appropriate comments.

What are the requirements for high-quality code?

1. Lightweight

Lightweight code mainly refers to code that is low in complexity and easy to understand and maintain.

This is generally achieved by reducing code redundancy and improving code readability and maintainability. For example, avoid using too many nested statements, use simple data structures and algorithms as much as possible, avoid using complex programming language features, etc.

2. Low coupling (loose coupling)

Coupling refers to the dependencies between codes. Low-coupling or loosely-coupled code means that there are as few dependencies between codes as possible, and each part of the code can complete its function independently.

This makes the code easier to maintain and modify, because modifications to one part of the code will not affect other parts of the code. Methods to achieve low coupling mainly include modular design, using interfaces or abstract classes to hide implementation details, etc.

3. Easy to replace

Easily replaceable code means that when requirements change or a better implementation method appears, the original code can be easily replaced.

This requires code design with good scalability and flexibility, for example, using interfaces or abstract classes to define functions, using design patterns to organize code, etc.

4. Easy to delete

Easy-to-delete code means that when a certain part of the code is no longer needed, it can be easily deleted without affecting other parts of the code.

This also requires the code to be designed with good modularity and low coupling. Additionally, there needs to be good test coverage to ensure that removing code does not introduce new bugs.

How to write good code?

1. Develop and adhere to coding standards

Coding standards are a set of preset and agreed programming styles and code writing rules.

The content of this rule guide covers the naming method of variables, functions and classes, the use of spaces and indentation, the way to write comments, and the organization of code structure, etc. The main purpose is to ensure the consistency and legibility of the code so that others can read and understand the code more easily.

For example, the Python community has a very famous coding specification PEP 8. PEP 8 has a series of regulations on the format of Python code. For example, indentation should use 4 spaces and no tabs; the length of each line of code should not exceed 79 characters; variables and functions should be named in all lowercase letters, and separate words with underscores, etc.

2. Write notes

It is known that fish have a memory of only 7 seconds, while programmers only have a memory of three days for the function they coded.

If there are no comments during the programming process, then at the moment the code is completed, only the programmer and God will know its true function. After three days, I am afraid only God is left to understand the true meaning of this code.

To put it bluntly, code comments are explanatory supplements to the code functions and implementation logic. They are mainly used to enhance the readability and maintainability of the code.

Its application scenario is very clear, which is to add an explanation to the code during the programming process to facilitate future review.

However, the quality of comments is not equivalent to their quantity. Only concise and precise comments are a sign of high-quality code. Excessive comments are like background noise, which will interfere with code understanding. Therefore, an appropriate annotation strategy should be to annotate only critical parts and complex logic in the code.

Among other general benefits, comments help to quickly find and understand previously written code, thereby increasing code reusability.

3. Use meaningful naming

Naming, like comments, is a big problem for programmers.

If comments test the programmer's summarizing ability, then naming undoubtedly tests the programmer's imagination and creativity. There are many programmer friends around me who come up with weird names on a whim. When I was writing it, I felt good about myself and felt that the name was appropriate or convenient. But when I read the code, I was dumbfounded. What does this mean? Why should pasta be mixed with No. 24 concrete?

A good name should accurately reflect its function or purpose, rather than randomly using unclear references like list1 or func1. You will understand it after reading it. Just forgot the name.

If you want to solve the problem of naming, it is best to establish your own naming rules. Whether it is internal variables or global variables, people should be able to understand the meaning of the variables at a glance.

4. Avoid using global variables

Global variables are variables defined in the global scope of the program. They can be accessed and modified anywhere in the program. It seems convenient, right, but if global variables are used extensively, the entire programming environment will become complicated and confusing.

First of all, global variables violate the principle of encapsulation. Encapsulation is an important principle of object-oriented programming, which hides the internal details of an object to protect the external environment. Global variables can be modified anywhere, making it difficult to trace and understand the flow of your code. This means that you need to remember the state of the global variable and understand in which part of the program it will be changed.

Secondly, global variables lead to implicit coupling between functions. This means that the behavior of one function may depend on whether another completely unrelated function modifies a global variable. The code becomes difficult to understand and predict.

Finally, global variables can cause naming conflicts. If you use the same global variable name in different places, you may accidentally overwrite the global variable's value.

In contrast, using local variables and function parameters makes the code clearer and more maintainable. Local variables only exist inside a function, so you don't need to care about how they are used or modified elsewhere. Function parameters can clearly indicate the input and output of the function, making it easy to understand and test the function.

Therefore,Although global variables may be necessary in some cases, in most cases it is best to avoid using global variables as much as possible. If you need to share data between multiple functions, consider using function parameters, return values, or creating a class that contains this data. This will make your code clearer, easier to understand, and easier to test and debug.

5. Minimize duplication of code

In programming, avoiding code duplication is a very important principle, often calledDRY principle, that is, "Don't Repeat Yourself".

This means you should avoid writing duplicate or similar blocks of code, but instead identify recurring patterns and create reusable function or class replacements.

For example, create a function calculate_average that calculates an average, and you can call this function wherever you need to calculate the average, rather than writing the same code repeatedly.

Complying with the DRY principle hasthree major benefits:

  • Improve code readability: No repeated code makes the code easier to understand.
  • Reduce Errors: Use functions or classes to avoid errors caused by modifying duplicate code.
  • Increase productivity: Write once, use many times, saving time and effort.

6. Use version control system

A version control system is a system that records the modification history of a file or project so that specific versions can be referenced in the future.

Among them, Git is one of the most popular version control systems, which can help developers track and manage code changes and support multi-person collaboration. The main commands are git commit and git checkout.

git commitUsed to commit changes and append an explanation message.

When you have made changes to the code and want to turn these changes into a new "version", you can use the git commit command. This command saves your changes and appends a message of your own writing explaining the changes. This way you can clearly track the changes for each version, and the reasons for those changes.

git checkoutUsed to view or roll back to an earlier version.

This command allows you to view or roll back to an earlier version of the code. Use this command if you find a problem with the latest code, or just want to see what an earlier version looked like. After executing this command, your code base will be returned to the state of the version you selected.

There are three major benefits of using a version control system to write code:

1. Track code changes: You can clearly see every modification and why these modifications were made. If you find a problem with the code, you can roll back to an earlier version or compare the differences between different versions to find the source of the problem.

2. Support multi-person collaboration: Everyone can work on their own branch and then merge the modifications into the main branch. This way, everyone can work at the same time without interfering with each other.

3. As a code backup: Even if your computer has a problem or fails to save, you can restore your code from the version control system.

7. Test your code

Testing code is a key step in programming. It can ensure the function, performance and security of the code and ensure that errors are discovered in time.

Testing code has five major benefits:

1. Error detection: Find and fix errors before code deployment to prevent potential problems.

2. Quality improvement: Ensure the functionality, reliability and performance of the code, and improve the overall quality.

3. Efficiency improvement: Discover and solve problems in a timely manner to avoid major changes later and improve development efficiency.

4. Provide documentation: Test cases can be used as code usage examples to help understand and use the code.

5. Refactoring promotion: With tests, code refactoring can be carried out with more confidence, because tests will catch introduced errors.

8. Keep the code simple

Naturally, one of the goals of programming is to write clear, concise, and maintainable code. How to write a concise code depends entirely on the programmers' efforts, which requires practice and later modification.

9. Code review

Code review, also known as code review or source code review, is a quality assurance activity.

Developers examine, read, and understand other people's code to find and fix errors, optimize code design, improve code readability and maintainability, and share knowledge. This process can take place in different settings, such as in a conference or using a code sharing platform such as GitHub.

For example, on GitHub, developers conduct code reviews through Pull Requests (PRs), requesting others to check and merge changes. This mechanism allows team members to raise questions, suggestions, or fixes for new or modified code.

The benefits of code review include: discovering and fixing code errors, improving software quality and stability; optimizing code design, improving code readability and maintainability; sharing knowledge and best practices Best practices to improve team efficiency.

In addition, new employees can learn about the code base and project faster through code reviews, while developers can improve their skills by reviewing other people's code.

10. Code Refactoring

Code refactoring is the process of optimizing code, which includes steps such as decomposition, merging, and simplification. The purpose is to improve the quality, readability, maintainability, and reusability of the code.

Programmers often say "If your program runs, don't touch it." This is a bit self-deprecating, because sometimes the places and causes of bugs may be strange, and you really don’t know how to solve them.

However, the end result of the program is that it will become more and more difficult to finish as it gets to the end, and it may end up creating a mountain of shit code.

For example, in the game GTA5, there was an if statement that looped 1.98 billion times during loading, which seriously slowed down the loading speed of the game. It took 7 years for it to be repaired, for fear that other programs would crash if this string of code was changed.

Moreover, refactoring should not wait for a few months, but should be real-time and continuous. After writing a function, it is best to think about how to optimize and refactor it. The best time to revise an 800-word essay is the moment you finish writing it.

study method

1. Avoid reinventing the wheel

In the IT industry, the term "reinventing the wheel" is usually used to describe a pointless effort to rewrite some code or functions that have already been written by others.

But if there is already a way to solve the problem, then there is really no need to spend time and energy to create the same solution. Repeated work will only make people physically and mentally exhausted< a i=1>.

The reason why human civilization progresses is because we step on the shoulders of our predecessors and climb up. The same is true for programming.

Some programmers will disdain this kind of borrowing behavior and think it is very low. The real boss should do everything from scratch!

This idea is right, but the problem is that we are not big guys, we are just ordinary coders. Why not take a shortcut if there is a shortcut? Isn’t the point of the open source community to allow everyone to easily solve problems that have already been solved through sharing?

For example, suppose everyone had to build a car by themselves. How time-consuming and labor-intensive it would be. We need to figure out how to make tires, engines, braking systems, etc. from scratch. But in fact, we can simply buy a car that has already been produced and then customize it according to our own needs. This way, we can spend our time and energy on more important things, like driving our car to where we want to go.

There are now many open source libraries and frameworks for us to use, and they have helped us solve many common problems. We just need to take the time to learn how to use them instead of writing code from scratch. In this way, we can focus more time and energy on solving actual business problems instead of getting entangled in dealing with underlying technical issues.

The benefits to us of adhering to the concept of "avoid reinventing the wheel" are obvious.

Once, duplication of work is avoided and work efficiency is improved. Secondly,, you can avoid some common errors and bugs by using code that has been tested by others.

Simply put, programmers should use existing resources as much as possible instead of wasting time repeating what others have already done.

2. Read more official documents and other people’s codes

If you want to improve the quality of your code, the best way is to read more, learn more, and practice more, because many things are "learned on paper but only in practice."

Official documents and other people’s high-quality open source code can be said to be the best learning resources for programmers.

Official documentation is the most comprehensive and authoritative source of information provided by technology or software developers. It usually contains everything you need to know, including how to use the technology, the principles behind it, and answers to frequently asked questions.

Beginners' first impression of official documents may be that they are "difficult to understand", but this is not the case.

Official documentation generally starts with basic concepts and then gradually goes into more complex content. This structure helps us understand and learn a technology systematically. In addition, official documentation usually contains a lot of sample code, which we can use to understand the concepts and use them as a basis for practice.

By reading and practicing official documents, we can not only learn how to use technology, but also understand the design ideas behind the technology, which is very helpful for us to understand and master the technology.

Reading the code of excellent open source projects is the best way to learn and understand how to organize and build code effectively.

When we read deeply into other people's code, we will get some knowledge that books will not tell us, such as how to handle various errors and exceptions. Books and teaching videos teach us theoretical knowledge, and the codes produced in actual combat will tell us the problems we may encounter in the actual programming process and the ideas for solving these problems.

In addition, looking at more excellent cases can help us develop a good programming style.

3. Programming for search engines

The value of open source is that it builds a broad platform for developers, allowing them to share code, learn from others' excellent experiences, and at the same time modify and optimize other people's code to improve their programming level.

These experiences and lessons learned by predecessors or carefully crafted framework codes are all put on the Internet. Many times, the questions you are wondering about or the functions you want to implement are already online. You don’t have to think hard or bother other programmers. You only need to move the mouse to get the answer a>.

In this process, the search engine is like a large encyclopedia of knowledge, which stores a wealth of programming knowledge and problem-solving methods. You only need to enter keywords to find relevant information.

Some people may think that it is not a good person to only use search engines to find information without using their own brains to solve problems.

However, the reality is that if an ordinary programmer can use search engines proficiently, then he can immediately solve 99% of the problems he currently faces. As for why it is 99%, it is naturally because search engines are not omnipotent.

Sometimes the answers provided by search engines cannot completely solve your problem, or you need to spend a lot of time filtering and understanding the information.

But in any case, using search engine programming can indeed effectively improve efficiency and code quality. You can also refer to the best practices of others during the search process to avoid duplication of work. At the same time, you can learn the latest technologies, stay ahead of the technology, and find solutions to programming problems to enhance your problem-solving abilities.

Google, Stack Overflow and GitHub are three search tools commonly used by developers, which can solve most problems in the development process.

Google can provide a large amount of programming knowledge and tutorials, Stack Overflow is a community dedicated to providing answers to questions for programmers, and GitHub is an open source code hosting platform where you can find a large number of excellent codes and projects.

4. Take the first step

Even if you write junk code, you still have to write it first. If you don’t write, there will be nothing.

If you want to write high-quality code, you must first dare to write garbage code. Try to write out all the required code as much as possible, even if it seems confusing.

Just like writing, no matter how perfect the thoughts are in your mind, no matter how spiritually you think about writing, you have to write down your thoughts first. No matter what kind of poor language or poor writing style, you have to write these down first. Then you can modify it.

You have to accept that the requirements are constantly changing, and you have to write the code that can meet the requirements first, and then reconstruct it later.

So how do you change junk code into high-quality code?

Here is a principle that you can take a look at:

Open-Closed Principle (OCP)

The Open-Closed Principle (OCP) is one of the five basic principles of object-oriented design. Its core idea is that software entities (classes, modules, functions, etc.) should be open to extension and closed to modification.

In other words, when the software needs to change, the change should be achieved by extending the behavior of the software entity rather than by modifying the existing code.

"Open for extension" means that we should design a system that can accommodate new functions, which requires us to be forward-looking when designing the system and take into account the possible future needs and changes.

"Closed to modifications" means that once the system is completed, we should try to avoid modifying the existing code. Because modifications to existing code bring risks and may introduce new errors. If our system is designed well enough, then when new requirements come, we only need to add new code instead of modifying the old code.

In order to achieve this goal, we need to minimize the dependencies between modules as much as possible during design, so that changes in one module will not affect other modules. At the same time, we also need to use abstraction and encapsulation as much as possible to hide the specific implementation by defining interfaces or abstract classes, so that when the specific implementation changes, dependencies There is no need to change its code.

Guess you like

Origin blog.csdn.net/weixin_53909748/article/details/133603316