Finishing | Yu Xuan

Product | life program

In addition to the programming language debate, code quality is also a hot topic among programmers. Recently, the original vlogger @axB posted a topic about bad code, which has attracted the attention and discussion of many developers.

When it comes to code quality, most people cite reasons like “need to go live”, he wrote on Twitter. After years of practice, it was much harder to write high-quality code than to say, “Tomorrow night, by the end of the day, what the boss wants today.”

What puzzled him was that when the need was really urgent, programmers often worked overtime to catch up; And when code quality deteriorates, very little effort is made.

In his opinion, what really affects the quality of the produced code often involves two things. On the one hand, it is necessary to carry out long-term practice under the guidance of qualified theory, on the other hand, it is necessary to have enough psychological ability to resist pressure. People who write high-quality code are only busier than they are when they are trying to meet requirements.

How does bad code come about?

There are many reasons programmers write bad code, but the most common ones are: 1. 2. Not recognizing the importance of code quality and best coding practices; 3. Being careless, trying to cut corners, not thinking about future changes…

As for how the column code was created, netizens said:

  • Fresh out of college, struggling with no one to tell you what high-quality code is.
  • It is not because of time rush, but because people are too vegetables, usually thinking less, less experience.
  • There’s a huge gap in thinking, a huge level of differentiation, and not everyone can write high-quality code.
  • When the requirements are uncertain and the structural design is tweaked back and forth, the code becomes bloated and rotten.
  • Not having a contingency plan in place and not having a lot of practice leads to neglecting code quality in order to meet deadlines.
  • In essence, demand management is a problem, lack of professional ability of management will blindly expand the scope of demand, that is, to strive for “as fast as possible” more and faster, no matter how good and province.

What does bad code “look like”?

Bad code produced for fast delivery doesn’t give much thought to future changes, let alone post-maintenance. They usually have the following problems:

  • Difficult to read and understand: The most striking feature of bad code is that no one can quickly understand it. This means that if a developer wants to update the code, he or she will have to invest extra time in understanding the code first, whereas understanding the broken code makes it hard to add new code. As a result, many new developers lose their jobs because they don’t understand the old code, and older developers leave when faced with the existing mess and bad bad code.

Example:

system.whenTerminated.onComplete(result => session.close()) implicit val materializer: Materializer = Materializer.matFromSystem(system) val dataPath = args(0) var batchSize = 512 if (args.length > 1) { batchSize = Integer.valueOf(args(1)) } var skip = 0 if (args.length > 2) { skip = Integer.valueOf(args(2)) } val lines =  scala.io.Source.fromFile(dataPath) try { import session.profile.api._ val parallels = Runtime.getRuntime.availableProcessors val source = Source.fromIterator(() => lines.getLines()) val action = source .map({ line: String => val number = counter.incrementAndGet() (number, line) }) .drop(skip) .mapAsync(parallels)(tuple => Future(decode(tuple._1, tuple._2))) .filter(_.isDefined).map(_.get) .grouped(batchSize) .mapAsync(1)({ articles => val max = articles.map(_.line).max val min = articles.map(_.line).min println(f"group of articles ${articles.size} [$min, $max]") Future.sequence(articles.map(a => nonExists(db, a))) .map(articles => articles.flatten) .recover({ case err: Exception => println(f"unexpect error $err when check in [$min, $max]")Copy the code
  • Contains many levels of nested blocks such as if-else statements and loops: Developers often use nested blocks such as if-else statements and loops to get the desired result quickly. And when the program compiles, the developers forget to optimize the program.

Example:

anchors foreach { anchor => if (anchor.hasAttr("href")) { val href = anchor.attr("href") val next = completeUrl(href) println(next) if (next.contains(domain) && ! roadMap.contains(url) && ! next.contains("/email-protection#")) { roadMap.add(next) if (process(next)) { println(f"processed $next") Thread.sleep(sleep) } else { println(f"skip $next") } } else { println(f"skip $next") } } }Copy the code
  • Misnamed methods and variables: To save time, developers often use variable/method names such as X, Y, Z, or ABC. This is a bad idea, because developers may remember what they do at the moment and forget it a few days later when they update the same piece of code. If you were anyone else, you would have no idea what they meant.

Example:

x = "abdon"
y = 314
z = 151
r = f(x).f2(y).f3(z)
Copy the code
  • Unnecessary code comments: Writing comments is a good habit, but keep your priorities straight. If you add too many, it’s easy to make the reader skip every comment, which can result in important comments being ignored.

Example:

Class Foo {// yun Xing Cheng xu public void run() {// call Foo Foo (args); / / call ABC (args); If (exists(efg(c))){foo(x); } else {// dazhe(d)); }}}Copy the code

The above sample code is provided by Liu Xin

The dangers of bad code

“What if the code sucks?” “, “It doesn’t matter, either the program or the person can run. Some people say that code is written for delivery, and when requirements are rushed online, the quality of the code is not guaranteed. Is that really the case? The answer must be “No.”

Programmers write code to solve problems, not to complete tasks. Low quality code is like a car with a problem. It runs, but it needs constant maintenance or it may not start at any time. Many programmers feel that the simplest code in the world is the code they have just written. And the worst code in the world, I wrote it a year ago.

Bad code looks good on the surface, but in the long run, it can be a ticking time bomb. Because when bad code goes wrong, here’s what happens:

1. It takes a lot of time and money to modify, and the cost will increase with the passage of time;

2. It is difficult or impossible to add new features;

3. Inability to predict where and when work will stop;

4. Negative impact on developer motivation…

At worst, bad code can lead to the project being scrapped.

Experts share solutions

In response to the problem, @baoyu xp, a former Microsoft Asp.Net most valuable expert and Internet technology blogger, posted a long post on weibo, sharing his expertise in solving the team’s bad code problem.

When a system is littered with rotten code, he argues, it’s time to think deeper. Are the requirements too bizarre? Too late? No design? Or a combination of factors?

Regarding these problems, he and his team made the following efforts:

  • Code review. All updated code is reviewed before being branch developed and merged into the trunk. Part of the review relies on tools and automated testing.
  • Do system design before you write code. Writing design documents allows developers to have a clear idea before implementation, follow best practices, and control code quality.
  • Pay technical debt on a regular basis. For old projects that are not worth maintaining, just patch them, don’t add new features or update them, as long as they work. For old projects that require long-term maintenance and often add new features, they need to be improved through refactoring. It is important to note that refactoring should first complement the automated test code and replace it module by module, not overwrite it and migrate it all at once.
  • The development model is a two-step process. During the two-week Sprint, the first week was just about the requirements of the product, and after the development was completed, it was deployed to the test environment for testing; Week two fixes bugs on various new features while doing purely technical tasks such as paying off technical debt, testing new technology stacks, and developing common components. This approach not only ensures code quality, but also ensures the continuous delivery of new product features.
  • Best practices for new or existing projects. After the completion of the architecture design, the team members first realized some basic functional modules based on the architecture design, and covered the basic scenes. As these modules are implemented, a good development practice is established. Code reviews are carried out at the same time as practice, and everyone can provide feedback and make adjustments to best practices based on that feedback. With best practices, others can not only copy and write good code; Code that does not conform to best practices can also be eliminated during the review phase.

Bad code can be written easily, but high quality code requires a lot of hard work, thinking, learning, and criticizing. What do you think of bad code? Have you done anything to improve the quality of your code? Welcome message exchange ~