A code refactoring method and apparatus

CN122884527APending Publication Date: 2026-10-09JIANXIN RONGTONG CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611179009.2
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-04
Publication Date
2026-10-09

AI Technical Summary

Technical Problem

不同的开发者对同一段代码可能产生不同的重构策略,且无法保证这些策略覆盖了原始代码中所有关键的语义约束

Benefits of technology

[0030]这样,通过语义注记表格将原始代码中易被忽视的隐性语义约束显式化、结构化,使重构策略的制定不再依赖开发者或大语言模型的一次性直觉判断,而是建立在客观的语义记录之上;测试用例与重构策略对应表将每个重构策略与对应的测试场景绑定,一致性检查表进一步确保每个策略都有对应的测试用例覆盖,从而系统性地消除了因语义理解偏差或测试遗漏导致的重构错误,进而提高了代码重构的准确性。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122884527A_ABST
    Figure CN122884527A_ABST
Patent Text Reader

Abstract

The application provides a code refactoring method and device, and relates to the technical field of data processing.In the method, firstly, a to-be-refactored method code is acquired, wherein the to-be-refactored method code comprises an original code file; then, a target semantic pattern in the original code file is scanned to obtain a semantic note table; then, a test case and a refactoring strategy corresponding table are written based on the semantic note table; then, a consistency check table is established by using the test case and the refactoring strategy corresponding table; then, executable unit test code is written based on the consistency check table; and finally, refactoring code is written based on the executable unit test code.Thus, the accuracy of code refactoring is improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of data processing technology, and in particular to a code refactoring method and apparatus. Background Technology

[0002] Code refactoring refers to the process of optimizing and adjusting the internal structure of code without changing its external behavior. Its goal is to improve code readability, maintainability, and scalability. As software systems continue to grow in scale, code refactoring has become a routine activity in the software development process.

[0003] In existing code refactoring practices, the following process is typically followed: Developers read the original code, judge based on experience which parts can be refactored, write the refactored code, and then verify the correctness of the refactoring by running existing test cases or adding new test cases. When a large language model is introduced to assist in refactoring, the process becomes: Developers provide the original code to the LLM, the LLM generates refactoring suggestions or refactored code, and the developers review and adopt them.

[0004] In existing technologies, developers primarily rely on their understanding and experience when deciding "how to refactor" and "which parts to refactor." This judgment is implicit and personal, lacking a structured, transferable, and verifiable form. Different developers may adopt different refactoring strategies for the same code, and there's no guarantee that these strategies cover all the key semantic constraints in the original code. When introducing LLM-assisted refactoring, it's easy to overlook the subtle semantic constraints implicit in the original code, making the issue of "ensuring these strategies cover all the key semantic constraints in the original code" even more prominent.

[0005] In conclusion, improving the accuracy of code refactoring is a problem that urgently needs to be solved by those skilled in the art. Summary of the Invention

[0006] In view of this, this application provides a code refactoring method and apparatus, which aims to improve the accuracy of code refactoring.

[0007] Firstly, this application provides a code refactoring method, including: Obtain the code of the method to be refactored; the code of the method to be refactored includes the original code file; The target semantic patterns in the original code file are scanned to obtain a semantic annotation table; Based on the semantic annotation table, a table corresponding to test cases and refactoring strategies is compiled. A consistency check table is established using the correspondence table between the test cases and the refactoring strategies. Write executable unit test code based on the aforementioned consistency checklist; Write refactoring code based on the executable unit test code.

[0008] Optionally, before writing the test case and refactoring strategy correspondence table based on the semantic annotation table, the method further includes: If the semantic annotation table is incomplete, the target semantic pattern in the original code file is scanned until the semantic annotation table is complete. The step of compiling a test case and refactoring strategy correspondence table based on the semantic annotation table includes: If the semantic annotation table is complete, then based on the semantic annotation table, write the test case and refactoring strategy correspondence table.

[0009] Optionally, before establishing a consistency check table using the test case and refactoring strategy correspondence table, the method further includes: If the test case and refactoring strategy correspondence table is incomplete, then based on the semantic annotation table, the test case and refactoring strategy correspondence table is supplemented until the test case and refactoring strategy correspondence table is complete. The step of establishing a consistency check table using the test case and refactoring strategy correspondence table includes: If the test case and refactoring strategy correspondence table is complete, then the consistency check table is established using the test case and refactoring strategy correspondence table.

[0010] Optionally, the consistency checklist associates each strategy number with a test case number and marks the coverage status. Before writing executable unit test code based on the consistency checklist, the method further includes: If the consistency check table does not meet the first preset condition, the consistency check table is supplemented based on the test case and refactoring strategy correspondence table until the consistency check table meets the first preset condition; the first preset condition is that each strategy number in the consistency check table has a corresponding test case number and the coverage status is not required to be supplemented. The step of writing executable unit test code based on the consistency check table includes: If the consistency checklist meets the first preset condition, then the executable unit test code is written based on the consistency checklist.

[0011] Optionally, before writing refactoring code based on the executable unit test code, the method further includes: If the executable unit test code cannot cover all the test cases corresponding to the consistency check table, then supplement the executable unit test code based on the consistency check table until the executable unit test code covers all the test cases corresponding to the consistency check table. The refactoring code based on the executable unit test code includes: If the executable unit test code covers all test cases corresponding to the consistency check table, then the refactored code is written based on the executable unit test code.

[0012] Optionally, after writing refactored code based on the executable unit test code, the method further includes: Using the path enumeration method, generate the first path enumeration table and the second path enumeration table: The first path enumeration table includes the execution paths and output results of the original code under all combinations of conditions; the original code file includes the original code; the second path enumeration table includes the execution paths and output results of the refactored code under the same combinations of conditions as the original code; The equivalence between the first path enumeration table and the second path enumeration table is determined, and the equivalence result is obtained.

[0013] Optionally, before generating the first path enumeration table and the second path enumeration table using the path enumeration method, the method further includes: Run all test cases corresponding to the consistency check table. If the refactored code fails, modify the refactored code based on the executable unit test code until the refactored code passes all test cases.

[0014] The method of generating a first path enumeration table and a second path enumeration table using path enumeration includes: If the refactored code passes all the test cases, then the path enumeration method is used to generate the first path enumeration table and the second path enumeration table.

[0015] Optionally, after determining the equivalence between the first path enumeration table and the second path enumeration table and obtaining the equivalence result, the method further includes: If the equivalence result does not meet the second preset condition, the refactored code is modified based on the executable unit test code; the second preset condition is that the equivalence result indicates equivalence.

[0016] Optionally, after determining the equivalence between the first path enumeration table and the second path enumeration table and obtaining the equivalence result, the method further includes: If the equivalence result satisfies the second preset condition, then the semantic annotation table, the test case and refactoring strategy correspondence table, the consistency check table, the executable unit test code, and the refactoring code are isolated for review.

[0017] Secondly, this application provides a code refactoring apparatus, comprising: The acquisition module is used to acquire the code of the method to be refactored; the code of the method to be refactored includes the original code file. The scanning module is used to scan the target semantic patterns in the original code file to obtain a semantic annotation table; The first writing module is used to write a table of correspondence between test cases and refactoring strategies based on the semantic annotation table; A module is established to create a consistency check table using the correspondence table between the test cases and the refactoring strategy. The second writing module is used to write executable unit test code based on the consistency checklist; The third module is used to write refactoring code based on the executable unit test code.

[0018] Optionally, the device further includes: The scanning module is used to scan the target semantic pattern in the original code file until the semantic annotation table is complete if the semantic annotation table is incomplete. The first writing module is specifically used for: If the semantic annotation table is complete, then based on the semantic annotation table, write the test case and refactoring strategy correspondence table.

[0019] Optionally, the device further includes: The first supplementary module is used to supplement the test case and refactoring strategy correspondence table based on the semantic annotation table if the test case and refactoring strategy correspondence table is incomplete, until the test case and refactoring strategy correspondence table is complete. The establishment module is specifically used for: If the test case and refactoring strategy correspondence table is complete, then the consistency check table is established using the test case and refactoring strategy correspondence table.

[0020] Optionally, the device further includes: The second supplementary module is used to supplement the consistency check table based on the test case and refactoring strategy correspondence table if the consistency check table does not meet the first preset condition, until the consistency check table meets the first preset condition; the first preset condition is that each strategy number in the consistency check table has a corresponding test case number and the coverage status is not required to be supplemented. The second writing module is specifically used for: If the consistency checklist meets the first preset condition, then the executable unit test code is written based on the consistency checklist.

[0021] Optionally, the device further includes: The third supplementary module is used to supplement the executable unit test code based on the consistency check table if the executable unit test code cannot cover all the test cases corresponding to the consistency check table, until the executable unit test code covers all the test cases corresponding to the consistency check table. The third writing module is specifically used for: If the executable unit test code covers all test cases corresponding to the consistency check table, then the refactored code is written based on the executable unit test code.

[0022] Optionally, the device further includes: The generation module is used to generate a first path enumeration table and a second path enumeration table using the path enumeration method. The first path enumeration table includes the execution paths and output results of the original code under all combinations of conditions; the original code file includes the original code; the second path enumeration table includes the execution paths and output results of the refactored code under the same combinations of conditions as the original code; The determination module is used to determine the equivalence between the first path enumeration table and the second path enumeration table, and obtain the equivalence result.

[0023] Optionally, the device further includes: The first modification module is used to run all test cases corresponding to the consistency check table. If the refactored code fails, the refactored code is modified based on the executable unit test code until the refactored code passes all test cases.

[0024] The generation module is specifically used for: If the refactored code passes all the test cases, then the path enumeration method is used to generate the first path enumeration table and the second path enumeration table.

[0025] Optionally, the device further includes: The second modification module is used to modify the refactored code based on the executable unit test code if the equivalence result does not meet the second preset condition; the second preset condition is that the equivalence result indicates equivalence.

[0026] Optionally, the device further includes: The isolation review module is used to isolate and review the semantic annotation table, the test case and refactoring strategy correspondence table, the consistency check table, the executable unit test code, and the refactoring code if the equivalence result meets the second preset condition.

[0027] Thirdly, embodiments of this application provide a computer device, including: a memory, a processor, and a computer program stored in the memory and executable on the processor. When the processor executes the computer program, it implements the code refactoring method as described in any of the embodiments of the first aspect of this application.

[0028] Fourthly, embodiments of this application provide a computer-readable storage medium storing instructions that, when executed on a terminal device, cause the terminal device to perform a code refactoring method as described in any of the embodiments of the first aspect of this application.

[0029] This application provides a code refactoring method. When executing the method, first, the code of the method to be refactored is obtained, including the original code file. Then, the target semantic patterns in the original code file are scanned to obtain a semantic annotation table. Next, based on the semantic annotation table, a test case-refactoring strategy correspondence table is written. Then, a consistency check table is established using the test case-refactoring strategy correspondence table. Then, executable unit test code is written based on the consistency check table. Finally, refactoring code is written based on the executable unit test code.

[0030] In this way, the implicit semantic constraints that are easily overlooked in the original code are made explicit and structured through the semantic annotation table. This makes the formulation of refactoring strategies no longer rely on the one-time intuitive judgment of developers or large language models, but is based on objective semantic records. The test case and refactoring strategy mapping table binds each refactoring strategy with the corresponding test scenario, and the consistency check table further ensures that each strategy has corresponding test case coverage. This systematically eliminates refactoring errors caused by semantic understanding bias or test omissions, thereby improving the accuracy of code refactoring. Attached Figure Description

[0031] To more clearly illustrate the technical solutions in this embodiment or the prior art, the drawings used in the description of the embodiment or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0032] Figure 1 A flowchart illustrating a code refactoring method provided in this application embodiment; Figure 2 This is a schematic diagram of the structure of a code refactoring device provided in an embodiment of this application; Figure 3 This is a schematic diagram of the structure of a computer device provided in an embodiment of this application. Detailed Implementation

[0033] The technical solutions in the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. This application provides a code refactoring method and apparatus, which relates to the field of data processing technology. The above are merely examples and do not limit the application field of the method and apparatus provided in this application.

[0034] Code refactoring refers to the process of optimizing and adjusting the internal structure of code without changing its external behavior. Its goal is to improve code readability, maintainability, and scalability. As software systems continue to grow in scale, code refactoring has become a routine activity in the software development process.

[0035] In existing code refactoring practices, the following process is typically followed: Developers read the original code, judge based on experience which parts can be refactored, write the refactored code, and then verify the correctness of the refactoring by running existing test cases or adding new test cases. When a large language model is introduced to assist in refactoring, the process becomes: Developers provide the original code to the LLM, the LLM generates refactoring suggestions or refactored code, and the developers review and adopt them.

[0036] In existing technologies, developers primarily rely on their understanding and experience when deciding "how to refactor" and "which parts to refactor." This judgment is implicit and personal, lacking a structured, transferable, and verifiable form. Different developers may adopt different refactoring strategies for the same code, and there's no guarantee that these strategies cover all the key semantic constraints in the original code. When introducing LLM-assisted refactoring, it's easy to overlook the subtle semantic constraints implicit in the original code, making the issue of "ensuring these strategies cover all the key semantic constraints in the original code" even more prominent.

[0037] The inventors, through research, proposed the technical solution of this application. First, the code of the method to be refactored is obtained, which includes the original code file. Then, the target semantic patterns in the original code file are scanned to obtain a semantic annotation table. Based on the semantic annotation table, a correspondence table between test cases and refactoring strategies is written. Then, a consistency check table is established using the correspondence table between test cases and refactoring strategies. Next, executable unit test code is written based on the consistency check table. Finally, refactoring code is written based on the executable unit test code.

[0038] In this way, the implicit semantic constraints that are easily overlooked in the original code are made explicit and structured through the semantic annotation table. This makes the formulation of refactoring strategies no longer rely on the one-time intuitive judgment of developers or large language models, but is based on objective semantic records. The test case and refactoring strategy mapping table binds each refactoring strategy with the corresponding test scenario, and the consistency check table further ensures that each strategy has corresponding test case coverage. This systematically eliminates refactoring errors caused by semantic understanding bias or test omissions, thereby improving the accuracy of code refactoring.

[0039] To enable those skilled in the art to better understand the present application, the present application will be further described in detail below with reference to the accompanying drawings and specific embodiments. Obviously, the described embodiments are only a part of the embodiments of the present application, and not all of them. Based on the embodiments of the present application, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present application. It should be noted that, for ease of description, only the parts related to the invention are shown in the accompanying drawings. Unless otherwise specified, the embodiments and features in the embodiments of the present application can be combined with each other.

[0040] See Figure 1 , Figure 1 A flowchart of a code refactoring method provided in this application embodiment includes: S101: Obtain the code of the method to be refactored.

[0041] First, obtain the code of the method to be refactored, which includes the original code file, the method name, and the current complexity index.

[0042] S102: Scan the target semantic patterns in the original code file to obtain a semantic annotation table.

[0043] The target semantic patterns in the original code file are scanned to obtain a semantic annotation table. The target semantic patterns include loop exit semantics, variable overriding priority chains, and switch exit semantics.

[0044] The scanning method for loop exit semantics is as follows: Scan all for / while loops and check if there is a break or return statement within the loop body. If there is no break, it means the loop will iterate through all elements and take the last matching value, which is an easily overlooked semantic constraint; if there is a break, it means the loop will stop as soon as a match is found. Record the exit semantics for each loop.

[0045] The variable override priority chain is scanned as follows: When the same variable is assigned a value multiple times by an if condition, the order of the assignments is recorded. Later assignments override earlier ones, so later assignments have higher priority. For example, if statusResult is assigned the values ​​DEFAULT, REJECTED, and APPROVED in sequence, the priority chain from low to high is DEFAULT, REJECTED, APPROVED.

[0046] The scanning method for switch fallback semantics is as follows: Identify case branches that lack break. These branches will "fall" into the shared logic of subsequent cases. This semantics is easily lost when refactoring into if-else.

[0047] Thus, a semantic annotation table is obtained.

[0048] After obtaining the semantic annotation table, verify whether the semantic annotation table is complete (when the exit semantics of all loops, the priority of all variable overriding chains, and the execution path of all run branches have been recorded). If the semantic annotation table is incomplete, scan the target semantic patterns in the original code file until the semantic annotation table is complete.

[0049] If the semantic annotation table is complete, then the implementation method in step S103 is executed.

[0050] S103: Based on the semantic annotation table, write a table that corresponds test cases and refactoring strategies.

[0051] Based on semantic annotation tables, a technical implementation scheme specification is written. The core content of the specification is a "test case and refactoring strategy mapping table". This table assigns a unique number to each refactoring strategy and indicates the corresponding test scenario and the expected number of test cases.

[0052] Verify whether the test case and refactoring strategy correspondence table is complete (each strategy number has a clear test scenario and expected number of test cases in the correspondence table). If the test case and refactoring strategy correspondence table is incomplete, supplement the test case and refactoring strategy correspondence table based on the semantic annotation table until the test case and refactoring strategy correspondence table is complete. If the table of correspondence between test cases and refactoring strategies is complete, execute the implementation method in step S104.

[0053] S104: Establish a consistency check table using the correspondence table between test cases and refactoring strategies.

[0054] Based on the Spec, test cases are designed according to the mapping table between test cases and refactoring strategies. A consistency check table is established, which associates each strategy number with a specific test case number and marks the coverage status.

[0055] Determine whether the consistency checklist meets the first preset condition, whereby each strategy number in the consistency checklist has a corresponding test case number and the coverage status is not required to be supplemented. If the consistency checklist does not meet the first preset condition, supplement the consistency checklist based on the test case and refactoring strategy correspondence table until the consistency checklist meets the first preset condition.

[0056] If the consistency checklist meets the first preset condition, then the implementation method in step S105 is executed.

[0057] S105: Write executable unit test code based on a consistency checklist.

[0058] Write executable unit test code based on test case documentation. There are two hard requirements here.

[0059] The first requirement is that Cartesian product conditional combination tests must be included. This means exhaustively listing all possible input combinations, rather than sampling tests. Each row in the path enumeration table can be directly mapped to a Cartesian product test case.

[0060] The second requirement is that specific verification tests must be included. Test data containing at least two matches must be constructed to verify whether the semantics of "iterating through all and taking the last match" are preserved after refactoring. The Cartesian product of all conditional combinations must be constructed to verify whether the reversed guard statements output the same as the original code in every combination.

[0061] Verify whether the executable unit test code covers all test cases corresponding to the consistency check table. If the executable unit test code cannot cover all test cases corresponding to the consistency check table, supplement the executable unit test code based on the consistency check table until the executable unit test code covers all test cases corresponding to the consistency check table. If the executable unit test code covers all test cases corresponding to the consistency check table, then the implementation method in step S106 is executed.

[0062] S106: Write refactored code based on executable unit test code.

[0063] When writing refactored code based on executable unit test code, for loops marked "iterate over all", when extracting them as independent methods, the pattern of assigning variables to iterate over all must be retained, and it is strictly forbidden to change it to "return when found". This is because although the two patterns behave the same in most cases, they will differ when there are multiple matches, the former returning the last one, and the latter returning the first one.

[0064] For logic with variable-overriding priority chains, the order of execution when refactoring into guard statements must be the reverse of the overriding chain. That is, the highest priority condition should be checked first, and the lowest priority condition should be placed last as a fallback. This is because guard statements return early; if a lower-priority condition is checked and returned first, the higher-priority condition will never be executed.

[0065] Run all test cases corresponding to the consistency checklist. If the refactored code fails, modify the refactored code based on the executable unit test code until the refactored code passes all test cases.

[0066] If the refactored code passes all test cases, the path enumeration method is used to generate a first path enumeration table and a second path enumeration table. The first path enumeration table includes the execution path and output results of the original code under all combinations of conditions, and the original code file includes the original code. The second path enumeration table includes the execution path and output results of the refactored code under the same combination of conditions as the original code.

[0067] Determine the equivalence between the first path enumeration table and the second path enumeration table to obtain the equivalence result, where the equivalence result includes equivalence, need to be confirmed, inequivalence, and cannot be determined.

[0068] If the equivalence result does not meet the second preset condition, the refactored code is modified based on the executable unit test code, wherein the second preset condition is that the equivalence result indicates equivalence.

[0069] If the equivalence result meets the second preset condition, the semantic annotation table, the test case and refactoring strategy correspondence table, the consistency check table, the executable unit test code, and the refactoring code are isolated for review. Specifically, the review agent and the modification agent have separate permissions. The review agent can only read and report, but cannot modify the source code. This avoids the structural risks brought about by the "find and fix" model. If the reviewer is also the modifier, then the review loses its independent value.

[0070] The review output is a structured JSON dataset containing two core fields: `need_confirm_items`, which lists anomalies requiring manual developer confirmation, and `recommendations`, which provides suggested modifications. This data is then fed back to the main console for the developers to make the final decision, rather than being automatically corrected by the system.

[0071] Finally, we obtained the refactored code, the specification design blueprint document, the test case document, and the review report JSON.

[0072] In the embodiments provided in this application, the method code to be refactored is first obtained, which includes the original code file. Then, the target semantic patterns in the original code file are scanned to obtain a semantic annotation table. Then, based on the semantic annotation table, a test case and refactoring strategy correspondence table is written. Then, a consistency check table is established using the test case and refactoring strategy correspondence table. Next, executable unit test code is written based on the consistency check table. Finally, refactoring code is written based on the executable unit test code.

[0073] In this way, the implicit semantic constraints that are easily overlooked in the original code are made explicit and structured through the semantic annotation table. This makes the formulation of refactoring strategies no longer rely on the one-time intuitive judgment of developers or large language models, but is based on objective semantic records. The test case and refactoring strategy mapping table binds each refactoring strategy with the corresponding test scenario, and the consistency check table further ensures that each strategy has corresponding test case coverage. This systematically eliminates refactoring errors caused by semantic understanding bias or test omissions, thereby improving the accuracy of code refactoring.

[0074] The code refactoring method provided by the embodiments of this application has been introduced above. The following is an exemplary description of the code refactoring method in conjunction with specific application scenarios.

[0075] Example 1: The `processDocCategory` method of the `DocCategoryService` class in a certain enterprise document management system is taken as the method to be refactored. This method has a cyclomatic complexity of 18, exceeding the preset threshold of 10, and contains two `for` loops without `break` statements and a variable override priority chain. Complexity management is assisted by a Large Language Model (LLM). The equivalence verification is performed using the method described in this invention, with the specific steps as follows: Pull the original code file of the processDocCategory method from the code repository, parse it to obtain the abstract syntax tree (AST), extract the loop structure, variable assignment chain, branch structure and switch / case structure, and record the method name processDocCategory and the current cyclomatic complexity of 18 as the benchmark.

[0076] The semantic annotation pre-module scans the original code line by line, identifies and structurally records three types of high-risk semantic patterns, and generates a semantic annotation table, the contents of which include: Iterate through the categories list: There is no break in the loop body. Exit semantics E(L1) = iterate through all. When there are multiple auditResult matching items, take the packStatus, categoryCode, and categoryDesc of the last matching item and assign them to the output variable. Find related documents: Again, no break, exit semantics E(L2) = traverse all, take the relatedDocType of the last matching item; Variable coverage chain V1: statusResult is assigned the values ​​DEFAULT, REJECTED, VIP_APPROVED, and APPROVED in sequence, with business priority APPROVED > VIP_APPROVED > REJECTED > DEFAULT; switch / case structure: no off-chain branches.

[0077] The implementation scheme specification is based on semantic annotation technology, which includes a "test case and refactoring strategy correspondence table": Strategy S1: Extract loop L1 into an independent method resolveCategory, while retaining the semantics of "traversing all and taking the last matching value"; Strategy S2: Extract loop L2 into an independent method resolveRelatedDocType, while preserving all semantics of the traversal; Strategy S3: Reconstruct the variable overriding chain V1 into guard statements, arranged in reverse order of the overriding chain (first check APPROVED, then VIP_APPROVED, then REJECTED, default DEFAULT). Strategy S4: Reduce the depth of the remaining nesting.

[0078] Based on the specification mapping table, write test case documents and create a "Specification Consistency Checklist": Write a JUnit 5 test class based on the consistency checklist, which includes: The Cartesian product parameterized test @ParameterizedTest covers 8 combinations of conditions in S3; Specialized test: Given a list of categories containing two auditResult="REJECT" entries, assert that the packStatus of the last matching item is returned, verifying that L1 does not degenerate to "return if found"; Specialized test: Input auditResult=REJECT&&bizType=VIP&&isApproved=true, assert statusResult=APPROVED, verify that the guard statement is reversed correctly.

[0079] Checkpoint C4 determines G(C4)=1 (covering all Spec policies and including Cartesian product tests).

[0080] LLM generates refactored code under semantic annotations and Spec constraints: when extracting the resolveCategory method, it uses a for loop to traverse all patterns without early return; statusResult is rewritten in guard statement form, with the order strictly in reverse of the overlay chain.

[0081] Example 2: The `transferConfirmingStatus` method of the `StatusTransferService` class in a certain transaction system is the method to be refactored. This method has a variable override chain where the assignment order of `result` is `CONFIRMING`, `APPROVED`, `DISCARD`, `FAIL`, with business priority `FAIL > DISCARD > APPROVED > CONFIRMING`.

[0082] Semantic annotation pre-scanning identifies variable coverage chain V1 and records the assignment order and business priority; Spec is written based on semantic annotations. Strategy S1 is to reconstruct the variable overriding chain into guard statements, with the order being the reverse of the overriding chain. Establish a consistency checklist and bind Cartesian product test cases to cover Cartesian product combinations of the three conditions: biz, trade, and approve; Write test code, including specific test verification: The combination of biz=CONFIRMING&&trade=ERROR&&approve=NOPASS returns FAIL; When writing refactoring code, the order of guard statements is as follows: first check if trade=ERROR→FAIL, then check if approve=NOPASS→DISCARD, then check if biz=CONFIRMING→APPROVED, with CONFIRMING as the default. Test passed, all path enumerations are equivalent, and isolation review passed.

[0083] The above are some specific implementations of the code refactoring method provided in the embodiments of this application. Based on this, this application also provides a corresponding apparatus. The apparatus provided in the embodiments of this application will be described below from the perspective of functional modularization.

[0084] See Figure 2 , Figure 2 This is a schematic diagram of a code refactoring apparatus provided in an embodiment of this application. The code refactoring apparatus 200 includes: The acquisition module 210 is used to acquire the code of the method to be refactored; the code of the method to be refactored includes the original code file. The scanning module 220 is used to scan the target semantic patterns in the original code file to obtain a semantic annotation table; The first writing module 230 is used to write a test case and refactoring strategy correspondence table based on the semantic annotation table; Module 240 is established to create a consistency check table using the test case and refactoring strategy correspondence table. The second writing module 250 is used to write executable unit test code based on the consistency checklist; The third writing module 260 is used to write refactoring code based on the executable unit test code.

[0085] Optionally, the device 200 further includes: The scanning module is used to scan the target semantic pattern in the original code file until the semantic annotation table is complete if the semantic annotation table is incomplete. The first writing module 230 is specifically used for: If the semantic annotation table is complete, then based on the semantic annotation table, write the test case and refactoring strategy correspondence table.

[0086] Optionally, the device 200 further includes: The first supplementary module is used to supplement the test case and refactoring strategy correspondence table based on the semantic annotation table if the test case and refactoring strategy correspondence table is incomplete, until the test case and refactoring strategy correspondence table is complete. The establishment module 240 is specifically used for: If the test case and refactoring strategy correspondence table is complete, then the consistency check table is established using the test case and refactoring strategy correspondence table.

[0087] Optionally, the device 200 further includes: The second supplementary module is used to supplement the consistency check table based on the test case and refactoring strategy correspondence table if the consistency check table does not meet the first preset condition, until the consistency check table meets the first preset condition; the first preset condition is that each strategy number in the consistency check table has a corresponding test case number and the coverage status is not required to be supplemented. The second writing module 250 is specifically used for: If the consistency checklist meets the first preset condition, then the executable unit test code is written based on the consistency checklist.

[0088] Optionally, the device 200 further includes: The third supplementary module is used to supplement the executable unit test code based on the consistency check table if the executable unit test code cannot cover all the test cases corresponding to the consistency check table, until the executable unit test code covers all the test cases corresponding to the consistency check table. The third writing module 260 is specifically used for: If the executable unit test code covers all test cases corresponding to the consistency check table, then the refactored code is written based on the executable unit test code.

[0089] Optionally, the device 200 further includes: The generation module is used to generate a first path enumeration table and a second path enumeration table using the path enumeration method. The first path enumeration table includes the execution paths and output results of the original code under all combinations of conditions; the original code file includes the original code; the second path enumeration table includes the execution paths and output results of the refactored code under the same combinations of conditions as the original code; The determination module is used to determine the equivalence between the first path enumeration table and the second path enumeration table, and obtain the equivalence result.

[0090] Optionally, the device 200 further includes: The first modification module is used to run all test cases corresponding to the consistency check table. If the refactored code fails, the refactored code is modified based on the executable unit test code until the refactored code passes all test cases.

[0091] The generation module is specifically used for: If the refactored code passes all the test cases, then the path enumeration method is used to generate the first path enumeration table and the second path enumeration table.

[0092] Optionally, the device 200 further includes: The second modification module is used to modify the refactored code based on the executable unit test code if the equivalence result does not meet the second preset condition; the second preset condition is that the equivalence result indicates equivalence.

[0093] Optionally, the device 200 further includes: The isolation review module is used to isolate and review the semantic annotation table, the test case and refactoring strategy correspondence table, the consistency check table, the executable unit test code, and the refactoring code if the equivalence result meets the second preset condition.

[0094] This application also provides corresponding devices and computer storage media for implementing the solutions provided in this application.

[0095] like Figure 3 As shown, the computer device 01 is represented in the form of a general-purpose computing device. The components of the computer device 01 may include, but are not limited to: one or more processors or processing units 03, system memory 08, and bus 04 connecting different system components (including system memory 08 and processing unit 03).

[0096] Bus 04 represents one or more of several bus architectures, including memory buses or memory controllers, peripheral buses, graphics acceleration ports, processors, or local buses using any of the various bus architectures. Examples of these architectures include, but are not limited to, the Industry Standard Architecture (ISA) bus, the Micro Channel Architecture (MAC) bus, the Enhanced ISA bus, the Video Electronics Standards Association (VESA) local bus, and the Peripheral Component Interconnect (PCI) bus.

[0097] Computer device 01 typically includes a variety of computer system readable media. These media can be any available media that can be accessed by computer device 01, including volatile and non-volatile media, removable and non-removable media.

[0098] System memory 08 may include computer system readable media in the form of volatile memory, such as random access memory (RAM) 09 and / or cache memory 10. Computer device 01 may further include other removable / non-removable, volatile / non-volatile computer system storage media. By way of example only, storage system 11 may be used to read and write non-removable, non-volatile magnetic media (…). Figure 3 Not shown; usually referred to as a "hard drive"). Although Figure 3 Not shown, a disk drive for reading and writing to a removable non-volatile disk (e.g., a "floppy disk") and an optical disk drive for reading and writing to a removable non-volatile optical disk (e.g., a CD-ROM, DVD-ROM, or other optical media) may be provided. In these cases, each drive may be connected to bus 04 via one or more data media interfaces. Memory 08 may include at least one program product having a set (e.g., at least one) of program modules configured to perform the functions of the embodiments of the present invention.

[0099] A program / utility 12 having a set (at least one) of program modules 13 may be stored in, for example, memory 08. Such program modules 13 include, but are not limited to, an operating system, one or more application programs, other program modules, and program data. Each or some combination of these examples may include an implementation of a network environment. Program modules 13 typically perform the functions and / or methods described in the embodiments of the present invention.

[0100] Computer device 01 can also communicate with one or more external devices 02 (e.g., keyboard, pointing device, display 07, etc.), and with one or more devices that enable a user to interact with the computer device 01, and / or with any device that enables the computer device 01 to communicate with one or more other computing devices (e.g., network card, modem, etc.). This communication can be performed through input / output (I / O) interface 06. Furthermore, computer device 01 can also communicate with one or more networks (e.g., local area network (LAN), wide area network (WAN), and / or public networks, such as the Internet) through network adapter 05. Figure 3 As shown, network adapter 05 communicates with other modules of computer device 01 via bus 04. It should be understood that, although... Figure 3 As not shown in the diagram, it can be used in conjunction with computer device 01 with other hardware and / or software modules, including but not limited to: microcode, device drivers, redundant processing units, external disk drive arrays, RAID systems, tape drives, and data backup storage systems.

[0101] The processor unit 03 executes various functional applications and data processing by running programs stored in the system memory 08, such as implementing a code refactoring method provided in the embodiments of this application.

[0102] It should be noted that, in this document, relational terms such as "first" and "second" are used only to distinguish one entity or operation from another, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Furthermore, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. Without further limitations, an element defined by the phrase "comprising one..." does not exclude the presence of other identical elements in the process, method, article, or apparatus that includes said element.

[0103] As can be seen from the above description of the embodiments, those skilled in the art can clearly understand that all or part of the steps in the methods of the above embodiments can be implemented by means of software plus a general-purpose hardware platform. Based on this understanding, the technical solution of this application can be embodied in the form of a software product. This computer software product can be stored in a storage medium, such as a read-only memory (ROM) / RAM, magnetic disk, optical disk, etc., including several instructions to cause a computer device (which may be a personal computer, a server, or a network communication device such as a router) to execute the methods described in various embodiments or some parts of the embodiments of this application.

[0104] The various embodiments in this specification are described in a progressive manner. Similar or identical parts between embodiments can be referred to mutually. Each embodiment focuses on its differences from other embodiments. In particular, the apparatus embodiments are basically similar to the method embodiments, so the description is relatively simple; relevant parts can be referred to the descriptions in the method embodiments. Some or all of the modules can be selected to achieve the purpose of this embodiment according to actual needs. Those skilled in the art can understand and implement this without creative effort.

[0105] The above description is merely an exemplary implementation of this application and is not intended to limit the scope of protection of this application.

Claims

1. A code refactoring method, characterized in that, include: Obtain the code of the method to be refactored; The method code to be reconstructed includes the original code file; The target semantic patterns in the original code file are scanned to obtain a semantic annotation table; Based on the semantic annotation table, a table corresponding to test cases and refactoring strategies is compiled. A consistency check table is established using the correspondence table between the test cases and the refactoring strategies. Write executable unit test code based on the aforementioned consistency checklist; Write refactoring code based on the executable unit test code.

2. The method according to claim 1, characterized in that, Before writing the test case and refactoring strategy correspondence table based on the semantic annotation table, the method further includes: If the semantic annotation table is incomplete, the target semantic pattern in the original code file is scanned until the semantic annotation table is complete. The step of compiling a test case and refactoring strategy correspondence table based on the semantic annotation table includes: If the semantic annotation table is complete, then based on the semantic annotation table, write the test case and refactoring strategy correspondence table.

3. The method according to claim 1, characterized in that, Before establishing the consistency check table using the test case and refactoring strategy correspondence table, the method further includes: If the test case and refactoring strategy correspondence table is incomplete, then based on the semantic annotation table, the test case and refactoring strategy correspondence table is supplemented until the test case and refactoring strategy correspondence table is complete. The step of establishing a consistency check table using the test case and refactoring strategy correspondence table includes: If the test case and refactoring strategy correspondence table is complete, then the consistency check table is established using the test case and refactoring strategy correspondence table.

4. The method according to claim 1, characterized in that, The consistency check table associates each strategy number with a test case number and marks the coverage status. Before writing executable unit test code based on the consistency check table, the method further includes: If the consistency check table does not meet the first preset condition, the consistency check table is supplemented based on the test case and refactoring strategy correspondence table until the consistency check table meets the first preset condition; the first preset condition is that each strategy number in the consistency check table has a corresponding test case number and the coverage status is not required to be supplemented. The step of writing executable unit test code based on the consistency check table includes: If the consistency checklist meets the first preset condition, then the executable unit test code is written based on the consistency checklist.

5. The method according to claim 1, characterized in that, Before writing refactoring code based on the executable unit test code, the method further includes: If the executable unit test code cannot cover all the test cases corresponding to the consistency check table, then supplement the executable unit test code based on the consistency check table until the executable unit test code covers all the test cases corresponding to the consistency check table. The refactoring code based on the executable unit test code includes: If the executable unit test code covers all test cases corresponding to the consistency check table, then the refactored code is written based on the executable unit test code.

6. The method according to claim 1, characterized in that, After writing refactored code based on the executable unit test code, the method further includes: Using the path enumeration method, generate the first path enumeration table and the second path enumeration table: The first path enumeration table includes the execution paths and output results of the original code under all combinations of conditions; the original code file includes the original code; the second path enumeration table includes the execution paths and output results of the refactored code under the same combinations of conditions as the original code; The equivalence between the first path enumeration table and the second path enumeration table is determined, and the equivalence result is obtained.

7. The method according to claim 6, characterized in that, Before generating the first path enumeration table and the second path enumeration table using the path enumeration method, the method further includes: Run all test cases corresponding to the consistency check table. If the refactored code fails, modify the refactored code based on the executable unit test code until the refactored code passes all test cases. The method of generating a first path enumeration table and a second path enumeration table using path enumeration includes: If the refactored code passes all the test cases, then the path enumeration method is used to generate the first path enumeration table and the second path enumeration table.

8. The method according to claim 6, characterized in that, After determining the equivalence between the first path enumeration table and the second path enumeration table and obtaining the equivalence result, the method further includes: If the equivalence result does not meet the second preset condition, the refactored code is modified based on the executable unit test code; the second preset condition is that the equivalence result indicates equivalence.

9. The method according to claim 8, characterized in that, After determining the equivalence between the first path enumeration table and the second path enumeration table and obtaining the equivalence result, the method further includes: If the equivalence result satisfies the second preset condition, then the semantic annotation table, the test case and refactoring strategy correspondence table, the consistency check table, the executable unit test code, and the refactoring code are isolated for review.

10. A code refactoring apparatus, characterized in that, include: The acquisition module is used to acquire the code of the method to be refactored; the code of the method to be refactored includes the original code file. The scanning module is used to scan the target semantic patterns in the original code file to obtain a semantic annotation table; The first writing module is used to write a table of correspondence between test cases and refactoring strategies based on the semantic annotation table; A module is established to create a consistency check table using the correspondence table between the test cases and the refactoring strategy. The second writing module is used to write executable unit test code based on the consistency checklist; The third module is used to write refactoring code based on the executable unit test code.