The sea is wide by diving, the sky is high as birds fly. Hey how are you! I’m Ed Qin. π
takeaway
I read this article a long time ago, and I thought the author analyzed it thoroughly and shared a lot of valuable lessons about good code. Beginners and veterans alike can benefit from this. I’ve seen a lot of programmers write code that is just a piece of code that a machine can recognize, often ignoring the very important concepts of rigor, readability, extensibility, maintainability, and so on.
We inform you! I republish this article in the hope that more people will see it and start to pay attention to the beginner’s mind of writing code and self-cultivation of programming.
Http://blog.2baxb.me /
1. In this paper,
I’ve been writing a lot of code lately, reviewing a lot of code, doing a lot of refactoring, and working on bad code for weeks. In order to express the emotions that have brought me to my breaking point several times in recent weeks, I decided to write an article about bad code. Here is the first part, talk about the causes and phenomena of bad code.
2. Bad code is easy to write
One of the things you often hear when you’re starting out as a programmer is that you need to focus on ABCD (requirements document/feature design/architectural design/understanding principles), and that writing code is just translating ideas into programming language, not a technical thing.
At the time, I would have dismissed the idea with a kind of chilly disdain: You’re just a bunch of idiots who don’t understand the importance of code quality, and sooner or later, you’re going to step on a hole. Ugh.
But after a few months, they don’t seem to be stepping much. And as the technology of programming continues to evolve, it’s bringing in more and more people who I used to think were idiots.
Languages are becoming more sophisticated, packages are becoming more sophisticated, and technologies are helping programmers produce code more efficiently. With layers of packaging, programmers don’t really need to know a single technical detail, just translate the requirements line by line.
A lot of programmers don’t know how to organize code, how to make it more efficient, what the underlying principles are, and they write code that looks like shit to me.
But that piece of fucking code actually works.
Even if I think their code is shit, from the point of view of someone who has never touched code (like your boss), the code has been compiled, tested, up and running for a month without a problem, what more can you ask for?
So, reluctantly, I have to admit that writing code itself isn’t that hard these days.
3. Bad code is bad code
But every once in a while, after the bad code writer leaves, things seem to change.
When I wanted to modify the function, I found that the program was filled with all kinds of incomprehensible logic and inexplicable bugs one after another after the modification. The person who took over the project began to work overtime aimlessly, and a cheerful and optimistic person gradually began to like to greet other people’s ancestors.
I’ve summarized a few types of bad code that are often fucked up:
3.1. Unclear meaning
Bad programmers tend to write code that doesn’t make sense; they don’t know what they’re doing.
Something like this:
public void save() { for(int i=0; i<100; I++) {// to prevent save failure, retry 100 times document.save(); }}Copy the code
For such programmers, I generally advise them to switch industries.
3.2. Don’t speak English
Speaking in English is the most common problem for beginners. The direct expression is to write a very simple code that others cannot understand.
Like this one:
public boolean getUrl(Long id) { UserProfile up = us.getUser(ms.get(id).getMessage().aid); if (up == null) { return false; } if (up.type == 4 || ((up.id >> 2) & 1) == 1) { return false; } if(Util.getUrl(up.description)) { return true; } else { return false; }}Copy the code
Many programmers like simple things: simple function names, simple variable names, code named after just a few words; Abbreviate when you can, omit when you can, merge when you can. The code they write is full of abbreviations for g/ S/GOS /of/ MSS that no one in the world understands, or a long list of consecutive calls that they don’t know what they’re doing.
There are also many programmers like complexity, all kinds of macro definition, bit operations and so on to write the hype, for fear that the code let others understand it will appear that their level is not enough.
Simply put, their code is written for machines, not for people.
3.3. Inappropriate organization
Improper organization is advanced bad code. Programmers who have written some code have a basic code style, but lack the ability to control larger projects and have no idea how code should be decoupled, layered, and organized.
The phenomenon of this antipattern is that it is common to see a piece of code being copied around the project; A file with a pile of code in it; A function is stacked with hundreds or thousands of lines; Or a simple function that twists and turns with dozens of functions, silently invoking some key logic in a creepy corner that is hard to find.
Most of this kind of code is complex, difficult to modify, often change the collapse; On the other hand, the people who create this code tend to change it, are afraid to create it, and would rather make it more complicated than reorganize it. When you look at a class with thousands of lines and you ask why don’t you extract the x logic, they say,
“But that would be one more class.”
3.4. Assumptions and lack of abstraction
Assume that this antipattern occurs more frequently and in more patterns than in the previous example, and that the originator is less likely to be aware of the problem. Such as:
public String loadString() {
File file = new File("c:/config.txt");
// read something
}
Copy the code
When the file path is changed, the code will look like this:
public String loadString(String name) {
File file = new File(name);
// read something
}
Copy the code
When more content needs to be loaded, it will look like this again:
public String loadString(String name) {
File file = new File(name);
// read something
}
public Integer loadInt(String name) {
File file = new File(name);
// read something
}
Copy the code
And then it might look something like this:
public String loadString(String name) {
File file = new File(name);
// read something
}
public String loadStringUtf8(String name) {
File file = new File(name);
// read something
}
public Integer loadInt(String name) {
File file = new File(name);
// read something
}
public String loadStringFromNet(String url) {
HttpClient ...
}
public Integer loadIntFromNet(String url) {
HttpClient ...
}
Copy the code
This type of programmer is usually the most productive person on the project team, but because of the amount of business development work they do, they don’t think twice. Their mantra is “I’m going to do XX requirements a day” or “Let’s do the requirements first and worry about the rest”.
The consequence of this anti-pattern is that it is often difficult to reuse the code. Faced with the deadline, programmers are eager to implement the requirements into the code, which is often a cycle: when writing the code, it is too late to consider reuse, and the code is difficult to reuse, resulting in a large amount of code to be written for subsequent requirements.
The accumulation of large amounts of code leads to issues of organization and style consistency, resulting in a legacy system where new functionality is largely copyable.
3.5. Anything else
There are many more types of bad code, and along the functional-performance-readable-testable extendable route, there are many bizarre examples.
So what is bad code? In my opinion, bad code consists of several layers:
- If only one person is maintaining the code, meeting the functional and performance requirements is sufficient.
- If you work on a team, it must be easy to understand and test, giving other people the ability to modify their own code.
- At the same time, extensibility is more important the deeper the code is in the system.
So when the underlying code in a team is hard to read, hard to test because it’s coupled to the logic at the top, or hard to reuse because it makes too many assumptions about usage scenarios, it’s still crap.
3.6. Adequate code
On the other hand, if a project’s code is hard to read, is it bad code? It’s hard to define. It may not be good, but is it bad? If the project is maintained by only one person throughout, and that person maintains it well, it seems to be “adequate code.”
Many projects may start as a small project of one person, and the focus of everyone is on whether the code can be smoothly implemented and completed on time.
After a while, when other people got involved, they found something wrong with the code. They couldn’t understand it and couldn’t move it. The demand side began to urge the line again, how to do? I had to be careful to just change the logic and not the structure, and then write in the comment that this implementation is ugly, and then refactor when I understand the internal logic.
Some time later, there is a similar need, want to reuse the logic inside, then realized that the code to do a variety of specific scenarios of special logic, reuse is very troublesome. I had to copy the code and change it in order to catch up. Problem solved, problem doubled.
Almost all bad code evolved from “good enough code.” The code didn’t change, the scenario in which the code was used changed, and the good enough code didn’t fit the new scenario, so it became bad code.
4. Refactoring is not a panacea
One of the most popular lies programmers tell programmers is that they are tight now and will refactor in X months when the project is less advanced.
Refactoring is undeniably a solution in some (very limited) scenarios, but after writing a lot of code, refactoring is often one of the most complex tasks in program development. Bad code that takes a month to write will take longer and take higher risks to refactor.
Experienced several unbearable large-scale refactoring, every refactoring is up in the group, open countless analysis and all the requirements in the group will dare to start after suspension, and often wailing everywhere in the process of reconstruction, almost every day out on a lot of unexpected problems, also will almost certainly when the online a few problems.
Technically, when refactoring complex code, you do three things: understand old code, break it down, and build new code. Old code to be refactored is often hard to understand; The excessive coupling between modules leads to the influence of the whole, it is not easy to control the scope of influence; Old code is not easy to test and the correctness of new code cannot be guaranteed.
The core issue here is that the complexity of the refactoring is not linearly related to the complexity of the code. For example, if you have 1000 lines of bad code and it takes 1 hour to refactor, then 5000 lines of bad code may take 2 or 3 days to refactor. Refactoring an out-of-control project is often less efficient than rewriting it.
Refactoring is tricky in terms of benefits, regardless of how it’s done: it’s hard to directly benefit from, and hard to quantify. It’s interesting to note that almost every book on refactoring has its own section on “How to Explain the Need for Refactoring to bosses”.
How much efficiency can refactoring improve? How much risk is reduced? It’s hard to answer. Bad code itself is not something that can be easily standardized.
For example, if a project’s code readability is poor, how much does it affect development efficiency?
You can say: it used to take 3 days to change a module, but after refactoring it will take 1 day. But what about “Why does it take three days just to do a database operation?” Bad code “bad” factors have uncertainty and development efficiency also vary from person to person, to prove this “really” can increase the two days of development time, often will become “I watched the 3 genius understand this function is what to do” or “it takes me three days to do such a simple change” the mental derangement to prove proposition.
On the other hand, many technical leaders recognize the need for code quality and refactoring and say, “Just refactor,” or “If you see a problem, refactor.” The last problem is solved, but the reality is that the costs and benefits of refactoring are still a blur, and without assigning you more resources, a clear goal, and a concrete approach, it’s hard to imagine anyone other than a clean code freak going through this unintelligible task.
This is often the case:
- People who don’t write code think you should refactor. Refactoring is easy, and it’s the responsibility of both new and old to do it.
- Veteran coders think that sooner or later you should refactor. Refactoring is hard, but it works for now. Don’t leave it to me.
- Novice code writers are thankful they don’t have bugs, and I don’t know how to refactor.
5. Writing good code is hard
Unlike writing bad code, there are many prerequisites for writing good code:
- Understand the functional requirements to be developed.
- Understand the operation principle of the program.
- Make a reasonable abstraction.
- Organize complex logic.
- A correct estimate of your own development efficiency.
- Keep practicing.
There are many methodologies for writing good code, but I think the core of writing good code is the low-sounding “constant practice.” I won’t expand on that here, but I’ll do that in the next chapter.
Many programmers write code for years with little improvement, and code still sucks for two main reasons:
- Context is one of the most important factors. It’s hard to understand what good code is in the presence of bad code, and most people who do know it will go with the flow.
- There are other subjective factors, such as personality, but programmers who write bad code tend to be nice people who love the company, work with their colleagues, and work hard — they just write bad code.
After a few years, it’s hard to convince people to improve their code, and you hear over and over again, “What good is that?” “Or” That’s how it used to be done? “Or something like that.
How about improving the quality of the code you recruit from the source?
I added whiteboard programming in the interview a while ago, and recently I added computer programming topics. I noticed that just because someone has worked for a few years, done a lot of projects, led teams, and posted a few articles doesn’t necessarily mean they wrote good code; On the other hand, if a person is good at coding, he or she is generally not bad at other things.
For example, I recently liked to use “Write a Line of code statistics tool” as a computer programming topic for my interview. The first thing a lot of people say when they look at this problem is, it’s too easy, it’s just writing code.
From a practical point of view, this problem recognition is not bad.
First of all, the questions are simple enough that even people who haven’t read books such as The Interview Handbook won’t be hurt. The expansibility of the topic is very good, even if you know the topic in advance, with different conditions, you can become a different topic. For example, it is required to count the number of lines by file type, or to improve the efficiency of statistics, or output the number of occurrences of certain words at the same time, and so on.
From the point of view of the investigation, the first is the basic tree traversal calculation method; Secondly, there is a certain amount of code, which can see the programmer’s ability to organize code and abstract the problem. Computer coding can be very simple to see if the candidate has not written a program for a long time; It also includes an understanding of application ease of use and performance.
Most importantly, the end result is a complete program that ALLOWS me to evaluate the programmer’s abilities against the standards of everyday work, rather than trying to figure out from a dozen lines of functions how that person might perform on a daily basis.
But even then, it’s hard to pat yourself on the back and say that this guy’s code is fine. After all, the interview is about the ability to write good code, not the ability to write good code in the future.
6. A pessimistic conclusion
Having said all that, there are really only two conclusions, as a programmer:
- Don’t expect anyone else to write quality code
- Don’t assume you’re writing quality code
Journal entry
Personally, I am also an experienced programmer with several years of development experience. Looking back and reading this article again, I feel closer to the author and can understand his aspirations and helplessness. It also gives us a clearer understanding of the principles and bottom lines that we programmers must stick to. To sum up, the salary of our programmers is quite good. If we can stick to our heart and keep moving forward, and give consideration to both soft and hard skills while developing well, it is completely foreseeable for the future. A lot of people say that we programmers are eating “youth” an industry, in my opinion, in fact, it is not. Say to eat “youth rice” person, that may be your growth rate and your age is not proportional to, in turn programmer this profession has the position that matches with it in different age stage, can say! If you’re good enough, you can’t retire.
Quotes.
The code is written for people and can be attached to the machine in a friendly way.
Scatter flowers πΈπΈπΈπΈ disk πΈπΈ
Click like π to see again, has become a habit! This series is constantly updated, and your one-key three-link is the biggest motivation for me to continue writing. If you have any comments and suggestions on this blog, welcome to leave a message! Welcome to disturb! π π
I am Qin Aide, a programmer in the Internet to survive!