Things about Rotten code (UP)

Source: Internet
Author: User

1. Summary

Recently wrote a lot of code, review a lot of code, but also done a lot of refactoring, in short, a bad code to work for a few weeks. In order to express some of the emotions that have reached the brink of collapse several times in the last few weeks, I decided to write an article about the bad code. Here is the last article, talk about the cause and phenomenon of the bad code generation.

  2. It's easy to write bad code

When I first entered the programmer's line, I often heard a point: you have to focus on ABCD (Requirements document/functional design/Architecture design/understanding principle), writing code only to translate ideas into programming language, is a matter of no technical content.

At that time I heard this point of view will have a similar to the high cold disdain: you are a bunch of stupid x, do not understand the importance of code quality, so go down sooner or later will step on the pit, yuck.

But a few months later, they didn't seem to be stepping on the pits. And as programming technology continues to evolve, it brings more people I used to think of as Dumb X to join the programmer industry.

Language more and more advanced, packaging more and more perfect, a variety of technologies are helping programmers to improve the efficiency of production code, relying on layers of packaging, programmers really do not need to understand the slightest technical details, as long as the requirements of the content of the translation out of the line can be?

Many programmers do not know how to organize the code, how to improve the efficiency of the operation, the underlying is based on what principle, they write out in my mind rotten into a piece of the same code.

But that one Tuo xiang like the code should be the fucking normal work.

Even if I think they write the code is Tuo Xiang, but from the point of view of people who do not touch the code (such as your boss), the code has been compiled, tested, on-line running for one months without problems, what do you want to ask for?

So, even reluctantly, it must be admitted that, to this day, writing the code itself is not so difficult.

  3. Rotten code is rotten code after all

But there are times when people who write bad code seem to be different after they leave.

Want to modify the function, but found that the program is filled with a variety of incomprehensible logic, changed after the inexplicable bug one by one, the person who took over the project began to aimless overtime, and originally a very optimistic and cheerful people gradually began to like greeting other ancestors.

I have summed up several types of rotten code that are often 艹 ancestors:

  3.1. Unclear meaning

Poorly-capable programmers are prone to writing meaningless code, and they don't know what they're doing.

Just like this:

public void Save () {    for (int i=0;i<100;i++) {        //Prevent save failed, retry 100 times        document.save ();}     }

For such programmers, I generally recommend that they change careers.

  3.2. Not speaking

Not speaking is the most frequent problem of beginners, the direct expression is to write a very simple code, others can not understand.

For example, the following paragraph:

 Public BooleanGETURL (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; }}

Many programmers like simple things: simple function names, simple variable names, and tossing and turning only a few words in the code, which can be abbreviated, omitted, and merged. The code written by this kind of person is filled with all sorts of G/S/GOS/OF/MSS or other abbreviations that no one in the world knows, or a long list of consecutive calls that don't know what to do.

There are many programmers like the complex, a variety of macro definitions, bit operations such as the hype, for fear that the code let others suddenly understand that will appear to be level enough.

To put it simply, their code is written to the machine, not to the human eye.

  3.3. Inappropriate organization

Inappropriate organization is a high-level of bad code, the programmer after writing some code, there is a basic code style, but for the larger project is not enough control, do not know how the code should be decoupled, layered and organized.

This anti-pattern phenomenon is often seen a piece of code in the project to copy, a large lump of code in a file, a function heap of hundreds of thousands of rows, or a simple function of seven turn eight around the tune of dozens of functions, in some difficult to find a small corner silently invoke some of the key logic.

This type of code is mostly complex, difficult to modify, often broken, and on the other hand, the people who created the code tend to modify the code, fear of creating code, they would rather let the original complex code step by step become more complex, and do not want to reorganize the code. When you're faced with a thousands of-line class and ask why you don't pull out a certain logic, they say:

"But that's one more class." ”

  3.4. Assumptions and lack of abstraction

In contrast to the previous example, it is assumed that this anti-pattern appears more frequently, more patterns, and more difficult for the initiator to realize the problem. Like what:

 Public String loadString () {    new File ("C:/config.txt");     // read Something}

When the file path changes, the code is changed to this:

 Public string loadString (string name) {    new  File (name);     // read Something}

When you need to load more content, it will change:

 Public string loadString (string name) {    new  File (name);     // Read something  public Integer loadint (String name) {    new  File (name);     // read Something}

It may become like this again:

 Publicstring loadString (string name) {File File=NewFile (name); //Read something} Publicstring LoadStringUtf8 (string name) {File File=NewFile (name); //Read something} PublicInteger loadint (String name) {File File=NewFile (name); //Read something} Publicstring loadstringfromnet (string url) {HttpClient ...} PublicInteger loadintfromnet (String url) {HttpClient ...}

Such programmers tend to be highly productive people in the project team, but a lot of business development work leads them to not think unnecessarily, and their mantra is: "I need to do xx every day" or "to finish the demand and then consider the others".

The consequences of this anti-pattern is often difficult to reuse code, in the face of deadline, the programmer is eager to put the requirements into code, and this is often a loop: write code when it is too late to consider the reuse, the code is difficult to reuse resulting in the need to continue to write a lot of code.

A little bit of accumulation of code has brought about organizational and style consistency problems, and finally formed a new function of the basic copy of the legacy system.

  3.5. Any more?

There are many different types of rotten code, along with features-performance-readable-testable-that can be extended to go on and see a lot of incredible examples.

So what is rotten code? Personally, the rotten code contains several levels:

    • If only one person maintains the code, it is enough to meet the functional and performance requirements.
    • If you work in a team, it must be easy to understand and test, so that other people have the ability to modify their own code.
    • At the same time, the more the code at the bottom of the system, the more important the extensibility is.

So, when the underlying code in a team is difficult to read, coupled with the logic of the upper layer, which makes it difficult to test, or makes too many assumptions about the use of the scene that makes it difficult to reuse, although the function is completed, it is still the same code.

  3.6. Enough code

and relative, if a project code is difficult to read, can you say this is rotten code? Difficult to define, may not be good, but can say it rotten? If the project is maintained by only one person, and that person is well maintained, it seems to be the "Enough Code".

Many projects at the beginning may just be a person responsible for the small project, the focus of attention is only the code can smoothly realize the function, completed on time.

Over a period of time, other people participate in the code to find the problem, do not understand, dare not move. Demand side began to urge the line, how to do? Had to be careful only to change the logic and not move the structure, and then write in the comments so that the implementation is very ugly, later understand the internal logic and re-construction.

After a while, there is a similar need, want to reuse the logic inside, then realize the code to do a variety of specific scenarios of the special logic, reuse is very troublesome. In order to catch up with the code and then change. The problem was solved and the problem doubled.

Almost all of the bad code evolved from "Enough Code", the code did not change, the use of the code scene changed, the original enough code does not conform to the new scene, then it becomes a rotten code.

  4. Refactoring is not a panacea

One of the programmers ' favorite lies with programmers is that they are now relatively tight, and after x months, the project is going to be a little looser and then refactored.

It is not possible to deny that refactoring is one of the means of solving problems in some (extremely limited) scenarios, but after writing a lot of code, refactoring is often the most complex work in the process of program development. It takes more time and higher risk to refactor a bad code that is written for one months.

Have experienced a number of large-scale reconstruction, each refactoring before the gathered up Group of experts, opened countless analysis will be in the group after all the suspension of demand, and the reconstruction process is often wailing everywhere, almost every day will be a lot of unexpected problems, on-line will almost certainly have a few problems.

Technically, there are three things to do when refactoring complex code: Understanding old code, breaking old code, and building new code. The old code that is to be reconstructed is often difficult to understand, and the excessive coupling between modules leads to reaching, which is not easy to control; The old code is not easy to test, which can not guarantee the correctness of the new code.

There is also a core problem, the complexity of refactoring is not linearly related to the complexity of the code. For example, there are 1000 lines of bad code, refactoring takes 1 hours, then 5000 lines of code refactoring may take 2, 3 days. Refactoring a project that is out of control is often less efficient than rewriting it.

Instead of concrete refactoring, refactoring is a cumbersome thing to benefit from: It's hard to bring direct benefits, and it's hard to quantify. Here is a very interesting phenomenon, the basic refactoring of the book without exception, there will be a separate chapter on "How to explain the need for the boss refactoring".

How much efficiency can be improved after refactoring? How much risk can be reduced? Hard to answer, the rotten code itself is not a simple standardization of things.

For example, the code for a project is poorly readable, so how much development efficiency does it affect?

You can say: Before changing a module to 3 days, after the reconstruction of 1 days will be. But how to deal with "is not to do a database operation, why 3 days" such issues? Rotten code "Rotten" factor has uncertainty, development efficiency also varies from person to person, want to prove that this thing "really" will increase the development time of 2 days, often instead will become "I see 3 days to understand this function is what" or "I make such a simple modification to spend 3 days" this kind of neuropathy will go to prove the proposition.

On the other side, many technical leaders are aware of the need for code quality and refactoring, "then refactor", or "refactor if you see a problem." The last problem is solved, but in fact the cost and benefit of refactoring is still a unclear, it's hard to imagine who else with the code cleanliness will perform this inexplicable task without assigning you more resources, no clear goals, no concrete methods.

The situation is often formed:

    • People who do not write code think that refactoring is a simple matter, and that it is the responsibility of both the newcomer and the old to refactor.
    • Write code veteran think should sooner or later should be reconstructed, refactoring is very difficult, now make use of, this matter don't fall on my head.
    • The novice who wrote the code didn't think it was a bug, and I didn't know how to refactor it.
  5. It's hard to write good code

Unlike writing bad code, there are a number of prerequisites to writing good code:

    • Understand the functional requirements to be developed
    • Understand how the program works
    • Make a reasonable abstraction
    • Organization of complex logic
    • The right estimate of your own development efficiency
    • Constant practice.

There are many methodologies for writing good code, but I think the core of writing good code is the "constant practice" that sounds very low. It's not going to start here, let's leave it to the next article.

A lot of programmers haven't made much progress after writing for years, and the code is still rotten to the eye, for two main reasons:

    • Environment is one of the most important factors, under the influence of rotten code is difficult to understand what is good code, know most people will choose to drift.
    • There is a personal character, such as the unknown subjective factors, write bad code programmer instead are some very good people, they often love the company unity colleagues approachable work hard-working-just the code sucks.

And after a few years of working hard to persuade them to improve the quality of the code, you will only repeatedly hear: "What is the use of it?" "or" is that what it used to be? "That kind of saying.

What about the quality of the code when it comes to raising the hiring?

The previous interview increased the Whiteboard programming, and recently added the problem of computer programming. Found a phenomenon: a manual for a few years, done a lot of projects, with the team, sent some articles, not necessarily can represent his code to write good, on the contrary, a person code written well, other aspects of the ability is generally not too bad.

For example, I recently like to use the "write a Code line statistics tool" as an interview on the Computer programming topic. Many people see the question after the first reflection is that the problem is too simple, this is not to write code.

Judging from the actual effect, the problem of recognition is still good.

First of all, the topic is simple enough, even if you have not seen the "interview book" and other books such as people will not suffer. and the topic of extensibility is very good, even if you know the topic in advance, with different conditions, can become a different topic. For example, it is required to count the number of rows by file type, or to increase statistical efficiency, or to count the number of occurrences of certain words, and so on.

From the point of view, the first is the basic Tree traversal algorithm, followed by a certain amount of code, you can see the programmer's ability to organize the code, the abstraction of the problem, the computer code can be very simple to see whether the applicant has not written a program for a long time, also includes the application of ease of use and performance understanding.

Most importantly, the final result is a complete program, I can judge the programmer's ability according to the standard of daily work, not from the more than 10-line function, the person in the daily work of the likely performance.

But even so, it's hard to pat the chest and say, this person writes the code quality is no problem. After all, the interview just means he has the ability to write good code, not that he will write good code in the future.

  6. The conclusion of pessimism

Having said so much, the conclusion is actually only two, as programmers:

    • Don't expect other people to write high-quality code
    • Don't think you're writing out a high-quality code.

If you see that there is no loss of hope, then look forward to the second part of this article, some suggestions and methods on how to improve the quality of your code.

Things about Rotten code (UP)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.