We’re always looking for ways to clean up the code, reduce complexity, and improve functionality. Refactoring points the way forward.

1. What is refactoring?

Martin Fowler, who has published two books on refactoring, says:

Refactoring is the process of modifying a software system in a way that improves only its internal structure without changing the external behavior of the code. Refactoring is an organized way of cleaning up code that minimizes the chance of introducing bugs. Essentially, refactoring means improving the design of the code after it has been written.

2,What are the benefits of refactoring?

The benefits of refactoring source code are innumerable. First, refactoring turns messy, incorrect, and/or duplicate code into clean code. It solves code standardization issues that can arise when multiple developers work together. Refactoring can improve readability, maintainability of source code, and overall structure and functionality. Refactoring makes it easier to extend and add new functionality to your code. Removing unnecessary code (such as duplicated code) reduces the memory used by the code and speeds up execution.

For example, in 2014, Kickstarter’s engineers were faced with a huge challenge: query performance was slowing due to the rapid growth in the number of users. To do this, they refactored MySQL queries to Redis, which reduced the load time by 100 milliseconds, thereby reducing the load time difference and improving the overall speed of the site.

3,Technical liabilities and refactoring

In short, refactoring is a way to eliminate or reduce technical liabilities.

Refactoring is critical to long-term code quality, security, and performance. Without regular refactoring, developers are saddled with significant technical debt. The fewer opportunities you have to refactor your code, the more technical debt you incur, and the harder it becomes to develop new features.

4,Indicators of refactoring

We can measure the priority of refactoring code by various metrics. With the help of metrics, we can plan our refactoring methodically, focusing on the most important tasks each time.

In addition, you need metrics to measure the effects of refactoring. Not only do we need to refactor inefficient code, but we can also add value by modifying inefficient code. To get real value, you need to do testing, both unit and functional. In addition, there are other indicators, such as a reduction in the number of bugs found and a reduction in loop complexity (the goal of refactoring is to reduce complexity). Methods or functions that are highly complex (such as methods or functions that are more than 350 lines long) are good refactoring objects.

In addition, we need to consider how to integrate refactoring into the broader team goals or milestones related to workflows and tasks.

5,Code Refactoring Examples

There are many examples of code refactoring, but for the sake of brevity, let’s look at the following:

Red, green and refactoring

Refactoring is all about unit testing. One of the most common forms is the Test-Driven Development (TDD) inherent to agile methods. You can write tests before you write code. In essence, it is up to the tests to drive the program and say what the code should do.

Red, green, and refactoring are an example of TDD:

  • Red: Writing a test suite with no implementation code is bound to fail.
  • Green: Writing implementation code just enough to pass the test suite.
  • Refactoring: Look for ways to optimize and improve your code.

Extraction method (also known as extraction function)

Move the code snippet from an existing method to a new method whose name makes it clear what it does. This technique helps reduce complexity and improve the readability of the code.

Extract variable

If you encounter an expression that is difficult to understand or that is repeated multiple times throughout your code, you can refactor the expression or part of it by extracting variables and putting it into a variable that is less complex and easier to understand. This reduces complexity and code duplication.

Branching by abstraction

Branching by abstraction allows you to make large-scale changes to a software system over time, and you can release the system periodically as you modify the code. This approach reduces the complexity of refactoring code on branches and avoids problems when merging code.

Methods combination

The code is too long to understand, and also too long to modify. Method composition refers to a series of operations that change methods into a sequential structure and remove duplicated code. These operations include inlining methods, inlining templates, replacing templates with queries, splitting temporary variables, and deleting assignments to parameters.

6,Tools for refactoring code

Do you need professional refactoring tools? Martin Fowler says automated tools are helpful but not necessary. He pointed out that:

“Many languages have IDEs that automate many common refactorings. These are invaluable tools that help me refactor my code faster. However, these tools are not essential, and I often write programs without tools to support me, taking one small step at a time, and testing them frequently to find errors.”

Many development environments can automate refactoring. Some common refactoring tools include:

  • Visual studio intellicode
  • Eclipse IDE
  • Spring Tool Suite 4
  • Rider
  • IntelliJ IDEA
  • SonarQube

7,Refactoring and the engineering manager’s dilemma

To address the issues that are driving the need for refactoring, first we need to understand how the company operates. Before you start refactoring, answer the following questions:

  • What are your priorities?
  • What is the speed of development?
  • Do developers feel pressure to deliver code quickly?
  • What are the procedures for resolving technical liabilities?
  • What types of code audits have been performed?
  • Do team members have the right refactoring skills?
  • What are the company’s documentation standards?

If you don’t address the underlying issues that drive the need for refactoring, the problem will only get worse.

Eight,Senior management support for refactoring

Your company may not be spending a lot of money on infrastructure and maintenance.

One might argue that the time spent on refactoring should be spent on new feature development.

However, we should still look at the benefits of refactoring and how they relate to workflow, customers, revenue, and business growth. Proper refactoring can improve code, deliver effective updates and much-needed functionality, and attract new and repeat customers. This way, software companies can stay competitive even after successful product launches.

A better way to get top management on board is to quantify how much time the team is currently spending fixing bugs or bugs in the original code. Be specific, like an hour a day? Two hours a day? Keep track of it for a week, and you’ll be surprised at how many weeks or months it takes your team to fix the remaining code every year.

9,Team Support and Refactoring: A Sprint or Marathon?

Having trouble refactoring within your team? Mention refactoring and moan? The most important signs of successful refactoring are planned, targeted, and documented actions. Ron Jeffries (one of the three founders of Extreme Programming) likens refactoring to clearing the road:

“Take the time to clear a path so that the next time we can go straight to the next feature we’re building, without having to bypass the weeds and bushes.”

However, he stresses that bad code takes a long time to clean up, and refactoring should be thought through:

“If we just improve the code we have and ignore the code we don’t currently cover, then we’re going to have to go back later.”

In the same Sprint, we often find that later functionality uses code that we cleaned up earlier. We immediately enjoy the benefits of refactoring. If we wait until we have accumulated a lot of technical debt before we start refactoring, the benefits we enjoy will be delayed and we may even waste energy in areas that are not very useful.

Andreas Klinger, a product engineer and chief technology officer who is a fan of Fix-It Friday, said:

“The rule of Fix-It Friday is simple: Unless the current project is on fire, Friday should be about refactoring. Let engineers choose their jobs. We should not micromanage away the pleasure. Some people will try new libraries. Some will fix the backlog bugs. Both are good jobs. We try to encourage people to balance these tasks.”

Either way, you need to think carefully and ask your team what code is most affecting their effectiveness.

  • Which code fixes have the most impact on the rest of your code?
  • Which problems get the most bang for your buck?

You’re unlikely to find a dedicated block of time for refactoring code, and refactoring code will inevitably sacrifice time you spent on other projects, but don’t underestimate the impact of doing small refactoring on a regular basis. Every little makes a mickle, and you will be richly rewarded in the end.

10,Documentation and refactoring

Documentation such as standardized naming conventions can keep everyone on the same page. Research by Xerox’s senior developers found that the lack of documentation was one of the biggest problems in refactoring.

Documenting the refactoring effort not only keeps track of the time spent, but also provides clarity to future team members.

Finally, you document your successes: What were the biggest successes of refactoring? Can these be considered for code reviews?

Author Alex Omeyer translator crescent | production | | CSDN (ID: CSDNnews) the original link: https://medium.com/swlh/the-u…

Recent hot article recommended:

1.1,000+ Java interview questions and answers (latest version of 2021)

2. I finally got the IntelliJ IDEA activation code through open source project. How nice!

3. Ali Mock tool officially open source, kill all the Mock tools in the market!

4.Spring Cloud 2020.0.0 is officially released, a new and disruptive version!

5. “Java development manual (Songshan edition)” the latest release, fast download!

Feel good, don’t forget with thumb up + forward oh!