There are two major difficulties in code refactoring. One is “archaeology”, which is how to quickly tease out the original logic of the code, and the other is “release”, which is how to make the new code can be published online stably without breaking down. Let’s take a look at a friend of mine and see how he managed to get his code up and running. And just to be nice, you’re my friend now.

Refactoring code can be a chore for many people. No may significantly effect way to precipitate effective systematic reusable technology gripper, no obvious increment for business, huge time and energy consumption, no test case, also can not get the test support, self-test is difficult to be fully, finally finished development difficult to online, the main reason is afraid of! It’s not that we’re not confident, of course, it’s real fear.

Why are you afraid to send code?

It was too difficult to code back to the complete product logic of the time

Whose code are you refactoring? Who knows whose it is! The code that allows you to refactor is probably not code you wrote, but ancient code, using an outdated technology stack. Often, of course, the development, testing, and even production of the year are nowhere to be found except in the annotated code. The words reveal helplessness, with a programmer’s conscience to remind the bearer, “be careful of the dirty things in front”. Read these words, you can only take back the mouth about to spit out the fragrance, silently leave the station, pour some hot water.

As you can see, comments not only help you read the code, but also serve as a warning to you to fix bugs as you refactor the code. Your attempt to tease out the original requirements through annotations fails, and you’re stuck praying that the business logic is not lost.

There is no self-test use case

Don’t assume that big companies have a complete system of tests with complete test cases, reality will hit you in the head. With frequent iterations, functionality has changed beyond recognition, and the old use cases are not available at all, let alone the old test cases. How to test yourself without using examples? It’s all in one’s imagination.

No test students follow up

Having an experienced tester involved in functional regression will certainly help your refactoring career, but the truth is that testers don’t want to do the dirty work. He couldn’t devote his time to a front-end initiated refactoring when he had unfathomable demands on his hands. No increment, no grip, pure strength, and they know it.

There is no stable release plan

In the absence of the premise of the above protection, if you can still be forced to go online, you will encounter greater problems, how to go online? Student: Just full substitution? What if something goes wrong online? The good news is that the rollback on the front end is very fast, but even a rapid rollback, from release completion to the discovery of a problem, can cause inmeasurable consequences when users are reminded to refresh the page, especially in scenarios that are frequently used and prone to dirty data. This is a common consequence of not having an effective release plan, and it can lead to back breakdowns, a year of extra work, late nights, lost hair, and nothing but the desire to start over somewhere else.

All of this leads to extreme insecurity. A programmer who is afraid to put his code online is like being woken up in the middle of the night by the sound of his one-month-old baby crying, and you just want to play dead. Besides, your job is often more than just refactoring. Doesn’t it make sense to write new requirements? You’re looking at a page that’s been refactoring for two weeks, and you’re getting less and less confident, more and more scared of half-refactoring, and more and more afraid of your boss’s question: “How’s the refactoring going?” You don’t look like a programmer.

Finally, at the end of the year, your refactoring work is still unfinished, and worse, it’s labeled as a “commitment” OKR, so you think about it and have a dream.

Go back to the beginning of the year when you were first asked to refactor.

Second, seek organizational guarantee

You refactor 177 jQuery pages using React. You immediately think of yourself as a person for a year, must be endless, at this moment, remember not to promise, must be realistic, or even toward the worst direction, so that the boss fully realize the difficulty of this task, do not have too high expectations. The most important thing is to ensure the input of manpower, there must be more students to participate in the effective division of labor is possible to complete this arduous task. People getting involved is just the beginning, as they will most likely go from enthusiastic to submissive, as described above, so make sure you put in the time and get your boss involved if necessary. Once your boss is involved, he or she will feel more involved and understand what everyone is going through. Then, there’s the old saying, “Remember, you’re an owner!” Do a good job in infrastructure construction, so that each student has the tools in hand, there is a safety guarantee, remove their worries at home is crucial. So, here are a few things you should do.

3. Prioritize the reconstructed pages

Through careful research, you find that 77 of these pages are frequently used by users and relatively complex pages, while the remaining 100 pages are mostly for adding, deleting, modifying and checking pages for development, which are not frequently used by users. So you make the following partition:Prioritization Once prioritized, different stable publishing strategies are used for different priority pages.

  • Complex high-frequency page: heavy pressure, meticulous restoration of original requirements, code picking, test students collate test cases, self-test according to test cases, test students regression of all functions. But in fact, this part of the page, can also be divided into two kinds of pages:
    • Edit page: this page is the highest risk, because once the backend interface to do the complete data validation, will produce the dirty data, or the wrong data is saved, resulting in abnormal operation, the consequence will be unimaginable, even a very short time rolled back, also can cause irreparable fault, therefore have to test in place like a new demand.
    • Display page: such a page will not affect the running time, will not produce dirty data, is a little lower risk of the page, in line with the principle of not bothering partners, after all, resources are limited, you can let the test to help you out of the complete use case, and then you test yourself, or find several students to help you test yourself.
  • High frequency simple page: self test, of course, it is best to kidnap a few often use this function of development, to help you a little bit, but their test will always be likely to have omissions, so you need the following steps to ensure.
  • Low-frequency operation and maintenance pages: selective reconstruction, because many pages basically do not have iteration, and the frequency of use is low, basically do not need reconstruction, even if there are new requirements, you can also do the reconstruction of new requirements, thinking that it does not take too much time.

Once you’ve divided up your pages, you’ll find that the amount of refactoring is much reduced because many pages don’t need to be refactored based on the “no need, no change” principle. And the above reconstruction of the page must do gray release.

Fourth, single measurement

The front end does not like to write single test, you probably summed up, mainly for the following reasons:

  • The current returns are not high.
  • Compared to the single test of the back-end interface, the front-end single test is relatively complex to write.
  • The front-end is more UI-oriented programming, but the UI changes so much that it is difficult to use TDD (test driven development) development mode.
  • There is no habit of writing single tests, probably because single tests increase workload, and there is no consciousness of writing pure functions, which is not conducive to testing.
  • Single-test tools are hard to learn and hard to use.

There are various reasons why the front end doesn’t like to write single tests, but when you’re refactoring complex pages, especially when the jQuery stack is refactoring to the React stack, single tests can be really useful.Here’s an edit pages, for example, consists of two parts: basic information and logic operation, when refactoring operation logic, you must first ensure the page after the refactoring in the preservation, saved data structure must be must be consistent with previous interface parameters, so the refactoring operation logic of the component when there will be a lot of data transformation logic.As you can see, in order to ensure that your new component does not interfere with the original function, you need to ensure that the original structure of the original data is preserved through the operation of the new component. At this point, you can write a single test to ensure this process.

describe('utils'.() = > {
  it('Flowchart: Conversion to submitted data transformForm'.() = > {
    const result = transformForm(canvasData);
    expect(result).toEqual(settingData);
  });

  it('Flow chart: Convert to desired data parseRuleSetData'.() = > {
    const [result] = parseRuleSetData(settingData, rules);
    expect(result).toEqual(canvasData);
  });

  it('Flowchart: Transform transformForm - parseRuleSetData repeatedly'.() = > {
    const [result] = parseRuleSetData(visualSettings, rulesData);
    const newResult = transformForm(result);
    expect(newResult).toEqual(visualSettings);
  });
});
Copy the code

Front-end unit tests are complex to write, but are really just simple UI tests. If you break the code down enough, with more functions and hooks, it’s easy to test.

Test cases

You are in a team where there are not enough test resources, and test cases seem to be a rare thing, especially in the trend of agile development, product functions change quickly, few tests will always maintain the original test case, often written and used and never found again. But test cases are really important in the context of refactoring, and the core problem they solve is to involve the test students in the quality assurance of refactoring and tease out the old logic together. This valuable test case can become the basis of your own testing, but also can provide you with a different perspective on the same function, if you see through the code is the implementation of the details of the logic, the test is to see the flow chart of the whole link. A lot of background systems have management state and running state points, management state, the front is very familiar with, but running state, testing is often more familiar with.

Six, self-test

You get the test cases, you can test yourself, but there’s a catch, and that’s if you rely entirely on the test cases given to you by your test classmates. It’s a big problem to just make sure that the test case is validated, because the person testing this feature might be a novice, might not be testing this feature all the time, and their test case might be superficial. So you need to expose the logic that’s not in the test cases that you’ve discovered through code archaeology to the test students and add it to the test cases. And if you find some logic that you can’t understand, you should understand him. Those dead corners that you don’t understand will often have big problems after being online. Don’t take any chances. Self-testing is very important, but often you feel like you’re done, even if you’re done, and then you’re busy doing something else instead of testing, thinking there’s more to it, and I’ll change it when they ask questions. This is a very common programmer mentality, and it’s hard to avoid because there are so many things. At this time you can find the same group of development students to help you point a little, first to solve those obvious problems, also be a serious and responsible programmer, do not let the test students give you too many low-level bugs.

Regression testing

It is a rare thing to have a test classmate to help you do the regression test of the function. You must cherish it and devote a lot of your time to it. The most important thing is to communicate more. Test students may not know all the logic. When doing regression testing, they need to develop and test and check each logic dead Angle repeatedly to make sure that they dare to go online. Of course, features that have tests to help you regression are likely to fail, so one trick is to pull tests into your refactoring. If the test knows the logic of such an important function, you can ask the other party with the mentality of consulting. If the other party does not understand, you can tell him. A responsible test should want to know the ins and outs of the important modules of the system they are responsible for.

Eight, gray release

Even if you do a lot of testing, it is possible that there are no missing points taken into account. At this time, grayscale is very important. Grayscale must have a grayscale tool. Refactoring is typically done on a page or block granularity per person. So your greyscale tool must include these features:

  • Configure users or user groups
  • Configure old routes and new routes
  • Configure the grayscale status prompt
  • New and old page automatic dot

On the gray configuration page, the parameters of the new and old dynamic routes need to be consistent so that the parameters can be passed on.Displays grayscale hints, provides a quick “back to old” button, and provides developer contact information for faster resolution.When a user accesses an old route, the system verifies whether the current user is in the gray scale based on the gray scale configuration. If the current user is in the gray scale, the system immediately switches to the new route and displays a gray scale prompt. If the reconstruction is a block in the page, it can provide a grayscale hit method, in the part of the page to call the block to make a judgment.

The grayscale strategy can be distributed according to the following user levels:

  • English: All project development, testing, designers, internal operations
  • L2: Core users, set up nail groups, observe user feedback, and timely solve user problems.
  • L3: Add more users appropriately until the number is full, delete the gray policy configuration.

After release, pay attention to the dot data:

Dot need to pay attention to, according to the dynamic route dot, and is divided into hit gray, click to use the old version, not in the gray of the three dimensions of the data, at the same time adjust gray users every day, so that you can ensure that the page is used by someone. If there are a lot of users to return to the old version of the function, then you have to find these users to understand the situation, in the end is a bug or uncomfortable interaction, one to one to solve the user problem, repeatedly to optimize your page, slowly expand the user gray range, until the old route access data PV is 0.

Ix. Full on-line

Full rollout is not about grayscale owners, but actually taking down the old page and removing the old code, and only then is the refactoring complete.

Ten,

After all kinds of difficulties and dangers, you finally put the good page reconstruction online, experienced this process, feeling a lot, just don’t do reconstruction in the future, do a good demand is not sweet? Looking at the whole process later, if you want to rebuild the page online, not only hard work, but also to overcome some of the weaknesses of human nature, to do the following:

  • Double Check: Involve other people. One more person can help you find more problems. In the face of reconstruction, don’t trust yourself, trust your partner.
  • Logic has no dead Angle: do not have to understand the code, unclear logic, according to the programmer’s sixth sense, uncertain will be a big problem.
  • Focus: Refactoring should not be done in fragments; focus on a chunk of time and do it to the end, or in a few days your own code will be unrecognizable.
  • Follow through: development is not important, full launch, and down the old page is finished.

Salute every warrior on the road to reconstruction.

Author: ES2049 / Blackstone

The article can be reproduced at will, but please keep this link to the original text.

You are welcome to join ES2049 Studio. Please send your resume to [email protected].