We’re always looking for ways to clean up code, reduce complexity, and improve functionality. And refactoring shows us 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 its internal structure without changing the external behavior of the code. Refactoring is an organized way to clean up your code and minimize 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?
There are countless benefits to refactoring your source code. First, refactoring can transform messy, incorrect, and/or duplicate code into clean code. It addresses code standardization issues that can arise when multiple developers work together. Refactoring improves readability, maintainability of source code, and overall structure and functionality. Refactoring makes it easier to extend code and add new functionality. Removing unnecessary code (such as duplicate code) reduces the memory used by the code and speeds up execution.
For example, in 2014, Engineers at Kickstarter were faced with a huge challenge: query performance was slowing down as the number of users grew rapidly. To do this, they refactored MySQL queries to Redis, reducing load times by 100 milliseconds, thus reducing load time differences and improving the overall speed of the site.
3,Technical liabilities and restructuring
In short, refactoring is a way to eliminate or reduce technical debt.
Refactoring is critical to maintaining code quality, security, and performance over time. Without regular refactoring, developers are saddled with huge technical liabilities. The less opportunity there is to refactor code, the more technical debt there is, and the harder it becomes to develop new features.
4,Reconstructed indicators
We can measure the priority of refactoring code by various metrics. With metrics, we can plan our refactoring in an orderly way and focus on the most important tasks each time.
In addition, you need metrics to measure 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 test, both unit and functional. In addition, there are other metrics, such as a reduction in the number of bugs found and a reduction in loop complexity (the goal of refactoring is to reduce complexity). Highly complex methods or features (such as methods or features with more than 350 lines) are good refactoring objects.
In addition, we need to consider how the refactoring fits into broader team goals or milestones related to workflow and tasks.
5,Code refactoring examples
There are many examples of code refactoring, but for brevity, here are a few:
Red, green and refactor
Refactoring is closely related to 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, tests should drive the program and explain what the code should do.
Red, green, and refactoring is an example of test-driven development:
- Red: Writing a test suite without implementation code will inevitably fail.
- Green: Write implementation code just right 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 into a new method whose name specifies its functionality. This technique helps reduce complexity and improve code readability.
Extract variable
If you encounter an expression that is difficult to understand, or that expression is repeated multiple times throughout your code, you can refactor the expression, or part of it, into a variable that is less complex and easier to understand by extracting the variable. This reduces complexity and code duplication.
Branch by abstraction
Branching off from the abstract allows you to make large incremental changes to the software system, and you can release the system regularly while modifying 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 too long to change. A method combination is a series of actions that change the method to a sequential structure and remove duplicate code. These operations include inlining methods, inlining templates, replacing templates with queries, splitting temporary variables, and removing assignments to parameters.
6,A tool for refactoring code
Do you need a professional refactoring tool? 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 very valuable tools that help me refactor code faster. However, these tools are not essential, and I often write programs without tool support, taking one small step at a time, and detecting errors with frequent testing.”
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 problem
To address the issues that cause the refactoring requirement, we first need to understand how the company operates. Before you start refactoring, answer the following questions:
- Which tasks come first?
- What is the pace of development?
- Do developers feel the pressure to deliver code quickly?
- What are the procedures for solving technical liabilities?
- What types of code reviews have been implemented?
- Do team members have appropriate refactoring skills?
- What are the company’s documentation standards?
If you don’t address the underlying issues that caused the refactoring requirement, the problem will only get worse.
Eight,Senior management support for refactoring
Your company may not have invested much in infrastructure and maintenance.
One might argue that the time spent refactoring should be spent developing new features.
However, we should still take a look at the benefits of refactoring and how they relate to workflow, customers, revenue, and business growth. Refactoring properly can improve code, deliver effective updates and much-needed functionality, and attract new customers and repeat customers. This is a way for software companies to stay competitive even after successful product launches.
A better way to get support from top management 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 tracking for a week, and you’ll be surprised at how many weeks or months it takes each year to fix the legacy code.
9,Team support and Refactoring: a Sprint or a Marathon?
Hard to refactor within your team? Mention reconstruction and cry out? The most important signs of a successful refactoring are planned, targeted, and documented actions. Ron Jeffries (one of the three founders of Extreme Programming) compares refactoring to clearing the way:
“Take some time to clear a path, so next time we can go straight to the next feature we’re building without having to go around weeds and bushes.”
However, he stresses that bad code takes a long time to clean up and that refactoring should be deliberate:
“If we only improve the code we have at hand and ignore the code we don’t have at the moment, then we will go backwards.”
In the same Sprint, we often find that later functionality uses the code we cleaned up earlier. We immediately enjoy the benefits of refactoring. If we wait to start refactoring until we build up a pile of technical debt, the benefits we enjoy will be delayed and we may even waste our energy in areas that are not very useful.
Andreas Klinger, a product engineer and cTO who is a fan of Fix-it Friday, said:
“The rule of Fist-it Friday is simple: Unless the current project is urgent, the work of Friday should be refactoring. Let engineers choose their jobs. We shouldn’t micromanage away that pleasure. Some people try new libraries. Some people fix a backlog of bugs. Both jobs are good. We try to encourage people to balance those tasks.”
Either way, you need to think hard and ask your team which code is most affecting their productivity.
- Which code fixes have the biggest impact on the rest of your code?
- What are the most rewarding problems to solve?
It’s unlikely that you’ll find a dedicated block of time to refactor code, and refactoring will inevitably sacrifice the time you spend on other projects, but don’t underestimate the impact of doing small scale refactoring on a regular basis. Every little helps a mickle, and you will be rewarded handsomly in the end.
10,Documentation and refactoring
Documents such as standardized naming conventions allow everyone to be on the same page. Research by senior developers at Xerox found that lack of documentation is one of the biggest problems with refactoring.
Documenting the refactoring effort not only records the time spent, but also provides an explanation for future team members.
Finally, you document your successes: What have been the biggest successes of refactoring? Can these be considered in code reviews?
The author Alex Omeyer translator crescent | production | | CSDN (ID: CSDNnews) links: the original medium.com/swlh/the-ul…
Recent hot articles recommended:
1.1,000+ Java interview questions and answers (the latest version of 2021)
2. Finally got the IntelliJ IDEA activation code through the open source project, how sweet!
3. Ali Mock tool officially open source, kill all the Mock tools on the market!
4.Spring Cloud 2020.0.0 is officially released, a new and disruptive version!
5. “Java Development Manual (Songshan version)” the latest release, speed download!
Feel good, don’t forget to click “like” + forward oh!