Artificial intelligence-based software refactoring method, device, equipment and storage medium

By analyzing code and user data and combining them with a large language model, a software refactoring strategy that balances technical optimization and business needs is generated. This solves the problems of low efficiency, high cost, and disconnect between refactoring solutions and business expectations in existing technologies, and achieves efficient and accurate software refactoring that adapts to changes in requirements during software iteration.

CN120540697BActive Publication Date: 2026-05-05SHENZHEN FENZHUAN TECH CO LTD
View PDF 2 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
SHENZHEN FENZHUAN TECH CO LTD
Filing Date
2025-05-21
Publication Date
2026-05-05

AI Technical Summary

Technical Problem

Existing technologies are inefficient and costly in software refactoring. Manual refactoring is prone to introducing errors and is difficult to cover all potential optimization points. Automated tools lack the ability to dynamically respond to business needs, and the generated code lacks a deep understanding of the original code context and business objectives, resulting in a disconnect between the refactoring solution and business expectations.

Method used

By analyzing code and user data, and combining large language models, a target refactoring strategy is generated that balances technical optimization and business needs. A code optimization detection model is used to identify code problems, and business expectations are extracted based on user interaction data to generate refactored code data. This ensures that the refactored code optimizes technical indicators while accurately matching the user's actual business scenario.

Benefits of technology

It improves the accuracy and efficiency of software refactoring, reduces the cost of secondary modifications caused by misunderstandings of requirements, and ensures that the refactored code meets the actual business needs of users and adapts to changes in requirements during the software iteration process.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120540697B_ABST
    Figure CN120540697B_ABST
Patent Text Reader

Abstract

This invention provides an artificial intelligence-based software refactoring method. The method includes: acquiring the current code data and user data of the software to be refactored; determining a target refactoring strategy based on the current code data and user data; generating refactoring code data corresponding to the target refactoring strategy based on a large language model; and refactoring the software based on the refactoring code data to obtain the target software. This invention analyzes code data and user data, considering both the code problems of the software to be refactored and user business expectations, to generate a target refactoring strategy that balances technical optimization and business needs. This avoids the problem of the separation between technical optimization and business goals in traditional methods, ensuring that the refactored code accurately matches the user's actual business scenario while optimizing technical indicators, reducing the cost of secondary modifications due to misunderstandings of requirements, and thus improving the accuracy and efficiency of software refactoring.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of artificial intelligence, and in particular to a software refactoring method, apparatus, device, and storage medium based on artificial intelligence. Background Technology

[0002] As software systems become increasingly complex and large-scale, software refactoring has become a crucial means of improving code quality and adapting to changing business needs. Traditional software refactoring primarily relies on developers' experience, involving manual analysis of code structure and identification of redundant or inefficient code (such as "code smells"). However, this approach suffers from low efficiency, high cost, and strong subjectivity. Especially in large-scale projects, manual refactoring is prone to introducing errors and struggles to cover all potential optimization points.

[0003] In recent years, some automated code refactoring tools (such as static code analyzers) have been proposed, but their functionality is limited to detecting specific types of code problems (such as code duplication, excessively long functions, etc.), lacking the ability to dynamically respond to business needs. In addition, existing tools usually only provide optimization suggestions and cannot generate refactored code that can be directly applied, still requiring developers to modify it manually.

[0004] Meanwhile, large language models (such as GPT and Codex) have shown potential in code generation, but their application in software refactoring still has limitations: on the one hand, the code generated by the model may lack a deep understanding of the original code context and business goals; on the other hand, existing methods do not consider user needs and code optimization goals, leading to a disconnect between refactoring solutions and business expectations. Therefore, how to leverage artificial intelligence technology to achieve efficient, accurate, and business-compliant automated software refactoring has become an urgent problem to be solved. Summary of the Invention

[0005] This invention provides an artificial intelligence-based software refactoring method, aiming to offer an efficient, accurate, and business-compliant automated software refactoring solution utilizing AI technology. By analyzing code and user data, considering both the code issues of the software to be refactored and user business expectations, this invention generates a target refactoring strategy that balances technical optimization with business needs. This avoids the disconnect between technical optimization and business objectives found in traditional methods, ensuring that the refactored code optimizes technical metrics while precisely fitting the user's actual business scenario. It reduces the cost of secondary modifications due to misunderstandings of requirements, thereby improving the accuracy and efficiency of software refactoring.

[0006] In a first aspect, embodiments of the present invention provide a software refactoring method based on artificial intelligence, the method comprising the following steps:

[0007] Obtain the current code data and user data of the software to be refactored, wherein the user data is the interaction data of the user during the use of the software to be refactored;

[0008] Based on the current code data and the user data, a target refactoring strategy for the current code data is determined;

[0009] Based on the large language model, generate the refactoring code data corresponding to the target refactoring strategy;

[0010] Based on the reconstructed code data, the software to be reconstructed is reconstructed, and the target software is obtained after the reconstructing is completed.

[0011] Optionally, determining the target refactoring strategy for the current code data based on the current code data and the user data includes:

[0012] The current code data is subjected to code optimization detection, and a first refactoring strategy that can be optimized is determined from the current code data;

[0013] The user data is used to extract business expectations, thereby extracting the user's business expectations for the software to be refactored, and a second refactoring strategy is determined in the current code data based on the business expectations.

[0014] Based on the first refactoring strategy and the second refactoring strategy, the target refactoring strategy for the current code data is determined.

[0015] Optionally, the step of performing code optimization detection on the current code data and determining an optimizable first refactoring strategy from the current code data includes:

[0016] The current code data is input into a pre-trained code optimization detection model for code optimization detection, and the code smells of the current code data are output.

[0017] Based on the code smells, an optimizable first refactoring strategy is determined from the current code data.

[0018] Optionally, the step of extracting business expectations from the user data to extract the user's business expectations for the software to be refactored includes:

[0019] Semantic extraction is performed on the user data to obtain multiple user semantics;

[0020] The user semantics are classified and processed to determine the user semantics related to the software to be reconstructed;

[0021] The user semantics related to the software to be reconstructed are used to generate user business expectations for the software to be reconstructed.

[0022] Optionally, determining the second refactoring strategy based on the business expectations in the current code data includes:

[0023] The business expectation and the current code data are respectively parsed into multimodal feature vectors to obtain a first multimodal feature vector and a second multimodal feature vector. The first multimodal feature vector corresponds to the business expectation, and the second multimodal feature vector corresponds to the current code data.

[0024] Based on the vector similarity between the first multimodal feature vector and the second multimodal feature vector, a second reconstruction strategy is determined in the current code data.

[0025] Optionally, determining the target refactoring strategy for the current code data based on the first refactoring strategy and the second refactoring strategy includes:

[0026] The common part between the first reconstruction strategy and the second reconstruction strategy is identified, and a first difference part that is different from the second reconstruction strategy is identified in the first reconstruction strategy, and a second difference part that is different from the first reconstruction strategy is identified in the second reconstruction strategy.

[0027] Perform a global verification on the first difference portion and the second difference portion to obtain the target difference portion that has been successfully verified globally.

[0028] The target difference portion and the common portion are determined as the target reconstruction strategy for the current code data.

[0029] Optionally, generating the refactoring code data corresponding to the target refactoring strategy based on the large language model includes:

[0030] Obtain the Abstract Syntax Tree (AST) corresponding to the current code data;

[0031] Based on the target reconstruction strategy and the AST abstract syntax tree corresponding to the current code data, construct the input file of the large language model;

[0032] The input file is input into the large language model to generate the refactoring code data corresponding to the target refactoring strategy.

[0033] Secondly, embodiments of the present invention also provide an artificial intelligence-based software refactoring apparatus, the artificial intelligence-based software refactoring apparatus comprising:

[0034] The acquisition module is used to acquire the current code data of the software to be refactored and the user data of the software to be refactored, wherein the user data is the interaction data of the user during the use of the software to be refactored;

[0035] The processing module is used to determine the target refactoring strategy for the current code data based on the current code data and the user data.

[0036] The generation module is used to generate refactoring code data corresponding to the target refactoring strategy based on the large language model;

[0037] The refactoring module is used to refactor the software to be refactored based on the refactoring code data, and the target software is obtained after the refactoring is completed.

[0038] Thirdly, embodiments of the present invention provide an electronic device, including: a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the computer program to implement the steps in the artificial intelligence-based software refactoring method provided in embodiments of the present invention.

[0039] Fourthly, embodiments of the present invention provide a computer-readable storage medium storing a computer program, which, when executed by a processor, implements the steps in the artificial intelligence-based software refactoring method provided in the embodiments of the present invention.

[0040] In this embodiment of the invention, the current code data and user data of the software to be refactored are obtained; based on the current code data and user data, a target refactoring strategy for the current code data is determined; based on a large language model, refactoring code data corresponding to the target refactoring strategy is generated; based on the refactoring code data, the software to be refactored is refactored, and the target software is obtained after the refactoring is completed. This invention analyzes code data and user data, considering the code problems of the software to be refactored itself and the user's business expectations, to generate a target refactoring strategy that balances technical optimization and business needs. This avoids the problem of the separation between technical optimization and business goals in traditional methods, ensuring that the refactored code, while optimizing technical indicators, accurately fits the user's actual business scenario, reducing the cost of secondary modifications caused by misunderstandings of requirements, thereby improving the accuracy and efficiency of software refactoring. Attached Figure Description

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

[0042] Figure 1 This is a flowchart of a software refactoring method based on artificial intelligence provided in an embodiment of the present invention;

[0043] Figure 2 This is a schematic diagram of the structure of a software reconfiguration device based on artificial intelligence provided in an embodiment of the present invention;

[0044] Figure 3 This is a schematic diagram of the structure of an electronic device provided in an embodiment of the present invention. Detailed Implementation

[0045] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0046] like Figure 1 As shown, Figure 1 This is a flowchart of an artificial intelligence-based software refactoring method provided in an embodiment of the present invention. The artificial intelligence-based software refactoring method includes the following steps:

[0047] 101. Obtain the current code data and user data of the software to be refactored.

[0048] In this embodiment of the invention, the aforementioned AI-based software refactoring method can be applied to a software refactoring platform. This platform comprises a server or distributed server, and deploys AI-based software refactoring applications and Large Language Models (LLMs) or LLM interfaces. These LLMs can be GPT, Wenxin Yiyan, Tongyi Qianwen, etc. The LLMs can validate and optimize code data based on user prompts, and can also output corresponding code data based on user prompts. The software refactoring platform can also include a code repository or a code repository interface, through which the code data of the software to be refactored can be obtained.

[0049] The source code files of the software to be refactored are read through code repository interfaces (such as Git, SVN) or local file systems, including but not limited to .java, .py, .js and other programming language files, and their code structure, function definitions, class relationships and comment information are extracted to obtain the current code data of the software to be refactored.

[0050] The aforementioned user data refers to user interaction data during the use of the software to be refactored, specifically user operation logs, user comment data, and user feedback data. User operation logs can include data such as user clicks on the software interface, navigation paths, function usage frequency, and operation sequence. User comment data can include user comments, messages, and ratings in the comment section while using the software. The aforementioned user feedback data can include text descriptions or questionnaires submitted by users based on the software's built-in feedback module. This interaction data will be collected in real-time or offline using tracking tools (such as Sentry and ELK), log collection systems, or user behavior analysis platforms (such as Mixpanel).

[0051] 102. Based on the current code data and user data, determine the target refactoring strategy for the current code data.

[0052] In this embodiment of the invention, current code data can be input into a pre-trained code optimization detection model (such as a deep learning-based code analysis tool) to identify and detect defects or optimizable code in the current code data. Detection results may include, for example, redundant code, inefficient structures, and design flaws.

[0053] Redundant code refers to duplicate functions and unused variables; inefficient structure refers to overly long functions and excessively nested conditional statements; design flaws refer to unclear class responsibilities and excessive coupling.

[0054] The first refactoring strategy can be generated based on the detection results, such as "splitting function A into two independent modules" or "removing unused dependency library B".

[0055] User data can be analyzed to extract users' business expectations for the software, and then a corresponding secondary restructuring strategy can be matched based on these expectations. Specifically, cluster analysis can be performed on user operation logs to identify frequently used functional modules (e.g., "users frequently trigger data export operations"); API call records can be statistically analyzed to locate high-latency interfaces (e.g., "the average response time of the order submission interface exceeds 2 seconds"); and natural language processing (NLP) can be performed on feedback text to extract keywords and intents, such as "slow speed," "missing functions," and "cannot capture long images." Based on the above analysis results, user business expectations for the software can be generated, such as: "optimize the execution efficiency of the data export function"; "add an API interface for batch deletion of orders"; "reduce timeout errors in the order submission interface"; and "optimize the UI."

[0056] After obtaining the business expectations, strategy matching can be performed based on these expectations, thereby associating the business expectations with the code logic. Specifically, the business expectations (such as "optimize data export efficiency") can be parsed into a first multimodal feature vector (semantic embedding vector); the current code data (such as the code of the data export module) can be parsed into a second multimodal feature vector (code structure graph embedding); the similarity between the two can be calculated to determine the scope of code that needs to be refactored, and a second refactoring strategy can be generated (such as "change the loop query in data export to a batch query").

[0057] The first refactoring strategy (technical optimization) and the second refactoring strategy (business self-adaptation) are merged. If there is a conflict (such as performance optimization leading to a decrease in code readability), priority arbitration is carried out through preset rules or reinforcement learning models to finally generate the target refactoring strategy.

[0058] 103. Based on the large language model, generate refactoring code data corresponding to the target refactoring strategy.

[0059] In this embodiment of the invention, the current code data can be parsed into an AST (Abstract Syntax Tree) and combined with the target refactoring strategy to construct a structured input file. For example, nodes in the AST that need to be modified (such as functions and loop blocks) are marked, and a strategy description corresponding to the target refactoring strategy is attached (such as "change the loop of function F1 to parallel computation"). The input file is input into a large language model (such as Code Llama or GPT-4). The model generates refactored code fragments based on the code context and strategy instructions, obtaining the refactored code data corresponding to the target refactoring strategy. For example, the serial loop for (i in list){...} in the original code is replaced with parallel computation list.parallelStream().forEach(...).

[0060] In one possible implementation, the syntax correctness of the generated code can be verified by a compiler or static analysis tool to ensure that there are no compilation errors, and the generated code without compilation errors is identified as correct.

[0061] 104. Based on the refactored code data, refactor the code of the software to be refactored, and obtain the target software after the refactoring is completed.

[0062] In this embodiment of the invention, after obtaining the refactored code data, the generated refactored code data can be compared with the original code (the difference comparison can be performed using the Diff tool), the target code segment can be automatically replaced, and the integrity of the unmodified part can be preserved.

[0063] In one possible implementation, automated test cases (such as unit tests and integration tests) can be run to verify the functional correctness and performance improvement of the refactored software.

[0064] The refactored code is deployed as target software through a continuous integration / continuous deployment (CI / CD) pipeline, and a refactoring report (such as optimization point statistics and performance comparison data) is generated.

[0065] In one possible embodiment, taking the order processing module of an e-commerce system as an example, the user frequently encounters the problem of "slow order export speed" during use, and the interactive data shows:

[0066] User operation log: An average of 500 order export operations are triggered per day, with an average waiting time of 8 seconds;

[0067] API call history: The standard deviation of the response time of the order export interface is large (1 to 15 seconds).

[0068] Feedback text: Users have repeatedly submitted complaints that "exporting orders takes too long, affecting work efficiency";

[0069] Comment text: Multiple users mentioned that "the wait time to view orders is too long".

[0070] Based on the above interaction data:

[0071] Code optimization analysis revealed that the order export function was performing database queries line by line (a code smell).

[0072] The business expectation is to reduce the order export time to less than 3 seconds.

[0073] The strategy matching identified a database query logic that needed optimization.

[0074] The target restructuring strategy is to "change the query from one row to a batch query and add pagination processing";

[0075] Generate JPA-based batch query code logic using a large language model;

[0076] After the restructuring, tests showed that the average time for order export was reduced to 2.1 seconds, and the user feedback problem resolution rate increased by 90%.

[0077] In this embodiment of the invention, the current code data and user data of the software to be refactored are obtained; based on the current code data and user data, a target refactoring strategy for the current code data is determined; based on a large language model, refactored code data corresponding to the target refactoring strategy is generated; based on the refactored code data, the software to be refactored is refactored, and the target software is obtained after the refactoring is completed. This invention analyzes code data and user data, considering the code problems of the software to be refactored itself and user business expectations, to generate a target refactoring strategy that balances technical optimization and business needs. This avoids the problem of the separation between technical optimization and business goals in traditional methods, ensuring that the refactored code, while optimizing technical indicators, accurately fits the user's actual business scenario, reducing the cost of secondary modifications due to misunderstandings of requirements, thereby improving the accuracy and efficiency of software refactoring. Furthermore, this invention can dynamically adjust the refactoring strategy based on continuously collected interaction data, adapting to changes in requirements during software iteration, and directly obtaining business-related expectations from user data without requiring product managers to submit business requirements.

[0078] It is understood that in the specific implementation of this application, data such as code data and user data are involved. When the embodiments in this application are applied to specific products or technologies, user permission or consent is required. Furthermore, the collection, use and processing of related data, as well as the training, deployment and invocation of algorithm models, must comply with the relevant laws, regulations and standards of the relevant countries and regions.

[0079] Optionally, based on the current code data and the user data, determining the target refactoring strategy for the current code data includes: performing code optimization detection on the current code data, and determining an optimizable first refactoring strategy in the current code data; extracting business expectations from the user data, extracting the user's business expectations for the software to be refactored, and determining a second refactoring strategy in the current code data based on the business expectations; and determining the target refactoring strategy for the current code data based on the first refactoring strategy and the second refactoring strategy.

[0080] In this embodiment of the invention, a dual-driven refactoring scenario combining static code optimization and dynamic business requirement analysis is considered, and a target refactoring strategy is determined based on current code data and user data.

[0081] Specifically, a pre-trained code optimization detection model (such as a Transformer-based neural network) is used. The training data for the code optimization detection model includes labeled samples from open-source code repositories (code snippets marked as "bad smells" or "normal"), and the model learns the correlation between code structure, syntax patterns and optimization requirements.

[0082] The current code data can be split into multiple code units by module or function; features (such as code complexity, dependency, and repetition rate) can be extracted for each code unit; after inputting into the model, probability values ​​are output to determine whether there are "bad smells" and their specific types.

[0083] For example: if the function processOrder() is found to contain 200 lines of code (exceeding the threshold of 150 lines), it is judged as an "overly long function"; if a circular dependency is detected between the classes UserService and OrderService, it is judged as a "tightly coupled design".

[0084] Based on the type of code smells, a predefined optimization rule library is matched to generate preliminary refactoring suggestions. For example, for "overly long functions," it is recommended to split them into sub-functions such as validateOrder() and calculatePrice(); for "tightly coupled designs," it is recommended to introduce an intermediary class OrderProcessor to decouple dependencies.

[0085] The initial refactoring strategy can be formatted, specifically by converting suggestions into structured instructions (such as JSON format), which include the location of the code to be modified, the type of optimization, and a reference template.

[0086] During the analysis of interactive data, high-frequency operation paths (such as "users trigger data export operations 300 times per day") can be extracted to identify functional hotspots; API response times (such as "payment interface has an average delay of 1.8 seconds") can be sorted to locate performance bottlenecks; and user feedback text (such as "hope to support PDF export format") can be classified by intent to extract functional expansion requirements.

[0087] Analysis results can be mapped to actionable refactoring goals. For example: operation log analysis → "improve the execution efficiency of data export function"; API latency statistics → "optimize the database query logic of payment interface"; feedback text parsing → "add PDF export function module"; and so on.

[0088] Input the desired business text (such as "optimize payment interface speed") into a text encoder (such as BERT) to generate the first multimodal feature vector (semantic vector).

[0089] The current code data (such as payment interface related code) is parsed into an abstract syntax tree (AST), and structural features are extracted through a graph neural network to generate a second multimodal feature vector (code structure vector).

[0090] Calculate the cosine similarity between the two vectors to determine the code module with the highest relevance to business expectations (such as the executePayment() function in the payment interface).

[0091] If the business expectation is performance optimization, the generation strategy could be "to change the serial query in executePayment() to a batch query"; if the business expectation is functional expansion, the generation strategy could be "to add a generatePDF() method to the ExportService class". This leads to the second refactoring strategy.

[0092] After obtaining the first and second reconstruction strategies, the overlapping optimization objectives are identified by comparing the first and second reconstruction strategies.

[0093] For example, the first strategy suggests "splitting the executePayment() function", and the second strategy suggests "optimizing the executePayment() query logic"; the common part is "refactoring executePayment()".

[0094] Identify code conflicts between the first and second refactoring strategies. For example, the first strategy suggests "reducing the number of database connections to reduce coupling," while the second strategy suggests "increasing concurrent connections to improve performance."

[0095] When there is a code conflict between the first and second refactoring strategies, arbitration is carried out through predefined rules or reinforcement learning models. This can be done by prioritizing business expectations (such as users explicitly requesting "performance first") or by using weight allocation (such as 40% weight for technical optimization and 60% weight for business requirements). The strategy selection model is trained based on historical refactoring effect data to output the optimal solution for the conflicting part, thus obtaining the target difference part.

[0096] Merge the common parts with the valid target differences to generate the final refactoring strategy as the target refactoring strategy. For example: Common part: "Split executePayment() into validate() and process()"; Difference part (validated): "Use batch queries and add connection pooling in process()"; Target refactoring strategy: "Refactor executePayment(), split the function and optimize the query logic".

[0097] Taking e-commerce system software as an example, if the inventory management module of the e-commerce system has performance problems and users report "high delay in inventory deduction".

[0098] Code optimization detection: The deductStock() function was found to contain complex transaction logic (code smell: "excessive transaction nesting").

[0099] The first refactoring strategy is: "Split the transaction into lockStock() and updateInventory()".

[0100] Business expectation extraction: Analysis of API logs revealed that the average latency of the inventory deduction interface was 2.5 seconds; business expectation was generated: "reduce the inventory deduction latency to less than 1 second"; multimodal matching located the database row lock contention issue in the deductStock() function.

[0101] The second restructuring strategy is generated: "Change row locks to optimistic locks and add a caching layer".

[0102] Strategy Integration: Common aspects: Both require modification of the deductStock() function; Differences: The first strategy focuses on code structure, while the second strategy focuses on concurrency mechanisms.

[0103] Global validation: Business requirements have higher priority, so the second strategy's concurrency optimization solution is adopted, while partially adopting the splitting suggestion of the first strategy;

[0104] The target strategy is to "split deductStock() into lockStock() and updateInventory(), and introduce Redis caching and optimistic locking mechanism in lockStock()".

[0105] This invention ensures that the refactoring solution simultaneously meets both code quality and user value through dual inputs of static code analysis (technology-driven) and user behavior data mining (business-driven); it adopts a verification method that combines rules and machine learning to avoid refactoring failures caused by policy conflicts; and it improves the refactoring targeting by accurately associating the business expectations described in natural language with specific code units through multimodal feature alignment.

[0106] Optionally, the step of performing code optimization detection on the current code data and determining an optimizable first refactoring strategy from the current code data includes: inputting the current code data into a pre-trained code optimization detection model for code optimization detection, and outputting code smells from the current code data; and determining an optimizable first refactoring strategy from the current code data based on the code smells.

[0107] In this embodiment of the invention, a scenario is considered where code smells are automatically identified and refactoring strategies are generated. Code optimization detection and the generation of a first refactoring strategy are then performed. Specifically, a code optimization detection model can be trained first, as follows:

[0108] First, prepare the training data. The training data can be collected from open source code repositories (such as GitHub) and enterprise code repositories. The annotation types include, but are not limited to: code smell types: excessively long functions, duplicate code, redundant condition judgments, tightly coupled classes, etc.; severity level: divided into three levels: high, medium and low according to the degree of impact on code quality (e.g., "duplicate code" is marked as "high" if it exists across modules).

[0109] Secondly, after obtaining the initial training data, the initial training data can be preprocessed. Data preprocessing can include standardizing the code (such as unifying indentation and deleting comments); parsing the code into an abstract syntax tree (AST) and extracting structural features (such as function call chains and class inheritance relationships); and converting it into a model input format (such as token sequences, graph structures, or vectorized representations).

[0110] In this embodiment of the invention, the code optimization detection model can employ a Transformer-based neural network or a graph neural network (GNN) to adapt to the serialization and structured features of the code.

[0111] Finally, the code optimization detection model is trained by inputting code snippets and their ASTs from the training data, enabling the model to learn the mapping relationship between code patterns and bad smell labels. Cross-entropy loss is used as the loss function, with the optimization objective being to minimize the bad smell classification error. Transfer learning is employed to enhance generalization ability, for example, by fine-tuning the pre-trained CodeBERT. The model's performance (e.g., accuracy, recall) is evaluated using a test set, and the training data distribution is adjusted for bad smell types with high false positive rates (e.g., "over-annotation") to obtain a well-trained code optimization detection model.

[0112] The current code data of the software to be refactored is split into independent units by module or function. For example, for Java projects, it is divided by class (.java file); for Python scripts, it is divided by function or class method. An Abstract Syntax Tree (AST) is generated for each code unit, extracting node types (e.g., function definitions, loop statements), code complexity (e.g., cyclomatic complexity, dependency count), and contextual information (e.g., call relationships). The code unit is then input into a trained code optimization detection model, which outputs the type of code smell and its confidence score. For example:

[0113] The cyclomatic complexity of the function generateReport() was detected to be 15 (threshold ≤ 10), and it was determined to be an "overly long function" with a confidence level of 92%; the mutual reference between classes DataParser and DataValidator was detected, and it was determined to be a "circular dependency" with a confidence level of 85%.

[0114] Post-processing of the results can be performed by using confidence filtering to retain only detection results with a confidence level higher than a set threshold (e.g., 70%), thus avoiding misjudgments that could interfere with strategy generation. Contextual analysis specifically aggregates cross-module code smells (such as duplicate code scattered across multiple locations) to generate global optimization suggestions.

[0115] The generation of the first reconstruction strategy mentioned above can be based on a strategy rule base. Specifically, the mapping relationship between bad smell types and reconstruction operations can be predefined, for example:

[0116] Bad Flavor Type Reconstruction Strategy

[0117] Break down excessively long functions into multiple sub-functions and extract common logic.

[0118] Repetitive code is abstracted into common functions or utility classes.

[0119] Tightly coupled classes can be decoupled by introducing interfaces or mediator classes.

[0120] Redundant conditional statements are merged into conditional branches, and the strategy pattern is used for refactoring.

[0121] Based on the above mapping relationship, the corresponding refactoring operation can be selected from the rule base according to the detected bad smell type. Furthermore, the strategy description can be refined by combining code context. For example, if "duplicate code" is detected in both module A and module B, the strategy generated is: "Merge validateUser() in module A and checkUser() in module B into a common method of the utility class UserUtils." When multiple bad smells are detected, priority ranking can also be performed, such as ranking the bad smells according to their severity level (e.g., high, medium, low), ensuring that critical issues are addressed first.

[0122] This invention achieves fine-grained identification of code structure defects by combining a pre-trained model with AST parsing, avoiding the coverage blind spots of traditional rule engines. Simultaneously, based on a rule base and a context-aware automatic adjustment mechanism, it generates actionable refactoring instructions, rather than general optimization suggestions. Furthermore, confidence filtering and severity grading ensure the reliability and rationality of the strategy.

[0123] Optionally, the step of extracting business expectations from the user data to extract users' business expectations for the software to be reconstructed includes: extracting semantics from the user data to obtain multiple user semantics; classifying the multiple user semantics to determine the user semantics related to the software to be reconstructed; and generating users' business expectations for the software to be reconstructed from the user semantics related to the software to be reconstructed.

[0124] In this embodiment of the invention, a scenario is considered that is suitable for mining refactoring requirements from the dynamic behavior of users using software and mapping them to code optimization goals, and business expectations are extracted and a second refactoring strategy is generated.

[0125] User data refers to user interaction data during the use of the software to be refactored, and may include: unstructured text data, semi-structured log data, and structured performance data. Unstructured text data includes: user feedback (e.g., "export speed is too slow"), work order descriptions, and chat logs. Semi-structured log data includes: operation logs (e.g., {timestamp: 2023-10-01, action: "export_data", duration: 8s}) and API call records. Structured performance data includes: CPU / memory usage and transaction processing time (e.g., {"api": " / submit_order", "avg_latency": "2.3s"}).

[0126] Pre-trained natural language processing models (such as BERT and RoBERTa) can be used to perform semantic embedding on unstructured text to extract key entities and intents. For example: Input: "Exporting orders takes too long, affecting work efficiency" → Extract the entity "Export orders" and the intent "Reduce time consumption". Named entity recognition (NER) models can be used to label business objects (such as "orders" and "payments") and operation types (such as "export" and "optimize").

[0127] It can perform regular expression matching and pattern recognition on semi-structured logs to extract key fields (such as operation type export_data, time taken 8s).

[0128] Build time-series analysis models (such as sliding window statistics) for structured performance data to identify outliers (such as " / submit_order interface latency suddenly increased by 50%)".

[0129] Specifically, a classification model can be trained, and a sample library labeled with user semantic types can be used. The sample library is shown in the table below:

[0130]

[0131] The classification model can be an intent classification model (such as one based on FastText or Transformer). The intent classification model is trained on the above sample library so that it can learn the semantic mapping between text and needs.

[0132] Textual semantics can be directly input into the classification model; logs and performance data can be converted into descriptive text (such as "export_data operation takes an average of 8 seconds") and then input into the model for classification.

[0133] The classification model outputs a category and confidence level for each user's semantic message (e.g., "Performance requirement - response speed", confidence level 88%); it filters out "irrelevant semantic" categories (e.g., those with a confidence level higher than 90%). Multiple semantic messages from the same user are analyzed in a conversation (e.g., after a user reports "slow export", they add "especially for large files"), and then merged into a complete requirement: "Optimize the performance of the large file export function".

[0134] The mapping from requirements to goals mainly includes performance requirement mapping, functional requirement mapping, and stability requirement mapping. For example, a performance requirement mapping might look like this: Input: "Exporting orders takes too long" + Log data: "The export_order interface takes an average of 8 seconds" → Quantitative goal: "Reduce order export time to less than 3 seconds." A functional requirement mapping might look like this: Input: "Want to support PDF export" → Quantitative goal: "Add a generatePDF() method to ExportService." A stability requirement mapping might look like this: Input: "Order submissions frequently time out" + API logs: "Timeout rate 15%" → Quantitative goal: "Optimize the timeout error rate of the order submission interface to below 2%."

[0135] Businesses expect structured representations that can be in a machine-understandable format, such as JSON.

[0136] Furthermore, the business expectation text (such as "reduce order export time") is encoded into a first multimodal feature vector (semantic vector); the relevant code (such as ExportService.java) is parsed into an AST and a second multimodal feature vector (code structure vector) is generated.

[0137] Calculate vector similarity to determine the code locations that need to be refactored (such as the loop query logic in the exportOrders() function).

[0138] The second reconstruction strategy generates an example as follows:

[0139] Extract the business expectation: "Optimize the performance of exportOrders()" → Second refactoring strategy: "Change row-by-row queries to batch queries and add a caching mechanism".

[0140] This invention extracts requirements from actual user behavior (operation logs, performance metrics), avoiding the lag and subjectivity of traditional requirements research; it combines multi-dimensional analysis of text, logs, and code structure to improve the accuracy and operability of business expectation extraction; through vectorized alignment technology, it accurately associates requirements described in natural language with specific code units, ensuring the refactoring strategy is targeted; it can continuously monitor user interaction data and dynamically update business expectations to adapt to changes in terminal requirements during software iteration.

[0141] Optionally, determining the second reconstruction strategy in the current code data based on the business expectation includes: parsing the business expectation and the current code data into multimodal feature vectors respectively to obtain a first multimodal feature vector and a second multimodal feature vector, wherein the first multimodal feature vector corresponds to the business expectation and the second multimodal feature vector corresponds to the current code data; and determining the second reconstruction strategy in the current code data based on the vector similarity between the first multimodal feature vector and the second multimodal feature vector.

[0142] In this embodiment of the invention, a scenario is considered in which user business expectations described in natural language are accurately associated with the code module to be refactored, and a targeted refactoring strategy is generated, so as to determine the second refactoring strategy based on the business expectations in the current code data.

[0143] Specifically, business expectations can be vectorized. First, the target description can be extracted from the generated business expectations, such as "optimize order export speed," and contextual information can be added, such as related code modules and performance metrics. Second, a pre-trained natural language encoding model (such as BERT or Sentence-BERT) can be used to convert the text into a semantic vector: input text → output 768-dimensional semantic vector (first multimodal feature vector). If the business expectations include quantitative metrics (such as "time taken 8 seconds → 3 seconds"), numerical features can be concatenated to the semantic vector to form a hybrid feature representation. The numerical features are concatenated according to the semantic type order corresponding to the numerical values, and the semantic type order is a preset order, such as sorting according to the priority of the semantic types.

[0144] Then, the current code data (such as OrderExportService.java) is parsed into an AST (Abstract Syntax Tree) to extract code structure features: function call relationships, loop / conditional branch structures, and class dependency graphs.

[0145] Graph embedding can be used for generation, specifically by using a graph neural network (GNN) to encode the AST and generate a code structure vector. Specifically, AST nodes (such as function definitions and variable declarations) can be mapped to initial embedding vectors; neighborhood node information is aggregated through the message passing mechanism of the GNN to generate a context-aware embedding for each node; pooling (such as mean pooling) is performed on all nodes in the graph to output the global structure vector of the code module (i.e., the second multimodal feature vector).

[0146] After obtaining the first multimodal feature vector and the second multimodal feature vector, calculate the cosine similarity between the first multimodal feature vector (business expectation) and the second multimodal feature vector (code module), set a similarity threshold (such as 0.7), and filter out code modules with high matching degree.

[0147] In one possible implementation, if the business expects to include specific keywords (such as "performance" or "concurrency"), higher weights are assigned to performance-related nodes (such as loops or database calls) in the code feature vector to improve matching accuracy.

[0148] Based on similarity ranking, identify code hotspots that require refactoring. For example, the business expectation of "optimizing order export speed" has a similarity of 0.85 with the OrderExportService.export() function, indicating that this function needs to be refactored first.

[0149] Based on the expected business type, a predefined refactoring operation library is matched. The predefined refactoring operation libraries are shown in the table below:

[0150]

[0151] This invention bridges the semantic gap between natural language requirements and code logic, achieving precise mapping from business objectives to code modules; it adaptively adjusts feature matching weights based on business expectation types, improving the scenario adaptability of strategy generation; through static analysis and dependency checks, it ensures the feasibility of the generated strategy and reduces the cost of manual correction; and by integrating multimodal information from text semantics, quantitative indicators, and code structure, it enhances the expressive power of complex requirements.

[0152] Optionally, determining the target reconstruction strategy for the current code data based on the first reconstruction strategy and the second reconstruction strategy includes: determining the common part between the first reconstruction strategy and the second reconstruction strategy; determining a first difference part in the first reconstruction strategy that differs from the second reconstruction strategy; determining a second difference part in the second reconstruction strategy that differs from the first reconstruction strategy; performing a global verification on the first difference part and the second difference part to obtain a target difference part that successfully passes the global verification; and determining the target difference part and the common part as the target reconstruction strategy for the current code data.

[0153] In this embodiment of the invention, considering the potential conflict between technical optimization goals and business requirements, and generating a high-availability refactoring scheme, the target refactoring strategy for the current code data is determined based on the first refactoring strategy and the second refactoring strategy.

[0154] Specifically, the first refactoring strategy is based on the code smell detection results, such as "splitting function A" and "removing redundant dependency B"; the second refactoring strategy is based on the multimodal matching results of user data, such as "optimizing the query logic of function A" and "adding a caching mechanism to function C".

[0155] The strategy texts of the first and second restructuring strategies are converted into structured operation instructions. For example: First strategy: "Split function A into A1 and A2"; Second strategy: "Add batch query to function A". Identify strategies with overlapping operation objects, such as both involving "function A" → the common part is "restructuring function A". First difference part (only proposed by the first strategy): "Remove redundant dependency B"; Second difference part (only proposed by the second strategy): "Add caching mechanism to function C".

[0156] Technical feasibility conflict detection is performed. For example, if the second refactoring strategy requires "introducing caching" but the code module has no caching framework dependencies, the code dependency tree is checked to verify whether the target technology stack is supported. Target priority conflict detection is also performed. For example, if the first refactoring strategy optimizes readability versus the second refactoring strategy optimizes performance, arbitration is conducted based on the priority of business requirements (e.g., user-specified "performance priority"). Logical contradiction conflict detection is also performed. For example, if the first refactoring strategy splits functions versus the second refactoring strategy requires maintaining function integrity, the code context is analyzed to determine whether splitting is permissible.

[0157] The aforementioned validation can include static validation and dynamic verification. Static validation uses code dependency analysis tools (such as Dependabot) to check the technical feasibility of the differences. For example, if the strategy is "introduce Redis caching" but the project does not include a Redis client library, it is marked as "requires adding a dependency"; if the added dependency conflicts with an existing version, a warning is generated and manual review is triggered. Dynamic validation can build a sandbox environment to simulate the execution of the differences. For example, for the strategy "change the serial loop of function A to parallel loop", unit tests are run to verify thread safety; if the test coverage is insufficient (e.g., <80%), it is marked as "requires supplementary test cases".

[0158] In one possible implementation, a classification model can be trained based on historical refactoring data. Inputs include conflict type, code context, and user priority; the output is a recommendation strategy. For example, given the input "performance optimization vs. readability optimization," the model recommends "performance optimization" with a 75% probability. The strategy with the highest probability recommended by the model is then incorporated into the final refactoring strategy.

[0159] After verification, if the verification passes, it is marked as the target difference and allowed to be included in the final strategy; if the verification fails, an alternative solution is generated or manual intervention is triggered. For example: the original strategy is: "Introduce Redis caching" → the alternative solution is: "Use Guava Cache in memory".

[0160] After obtaining the target differences and commonalities, the commonalities can be directly merged (deduplicated): overlapping operations are deduplicated and their logical order optimized. For example: commonalities: "Reconstruct function A" → merged instruction: "First split function A into A1 / A2, then optimize the query logic of A1". The differences can be selectively integrated; the target differences can be merged after being sorted by priority according to validation. For example: first difference (passed): "Remove redundant dependency B"; second difference (passed): "Add caching mechanism to function C"; merged strategy arranged in execution order: "Remove B first, then add caching".

[0161] After setting the target refactoring strategy for the current code data, a machine-executable refactoring plan can be generated based on the target refactoring strategy, such as code files in JSON, YAML, or other formats.

[0162] This invention verifies strategy conflicts from multiple perspectives, including code feasibility, target priority, and logical consistency, avoiding the limitations of a single rule; it predicts strategy risks through simulated execution, reducing runtime errors introduced by refactoring; it combines rule engines and machine learning to balance automation efficiency and decision accuracy; and it generates a structured refactoring plan, clarifying the execution order and constraints, thus improving implementation transparency.

[0163] Optionally, generating the refactoring code data corresponding to the target refactoring strategy based on the large language model includes: obtaining the AST (Abstract Syntax Tree) corresponding to the current code data; constructing an input file for the large language model based on the target refactoring strategy and the AST corresponding to the current code data; and inputting the input file into the large language model to generate the refactoring code data corresponding to the target refactoring strategy.

[0164] In this embodiment of the invention, the current code data can be input into the parser using a code parsing tool (such as the ast module) to generate a complete AST structure. The generated AST nodes include: class declarations, method definitions, method invocations, etc. After obtaining the AST abstract syntax tree, the nodes in the AST that need to be refactored (such as functions, loops, conditional branches, etc.) are marked according to the target refactoring strategy.

[0165] The Abstract Syntax Tree (AST) is serialized into a format such as XML or JSON. Graph embedding techniques are then used to convert the AST into feature vectors for use as numerical inputs for large language models.

[0166] In one possible implementation, the policy scope can be explicitly annotated in the input file. For example, indicator labels can be added to the AST nodes, such as... <refactortarget strategy="split_method" / > The label indicates that the large language model applies a strategy to that node.

[0167] The large language model mentioned above can be a general-purpose large language model (such as GPT-4), which can be used for instruction fine-tuning, or it can be a code-specific large language model (such as Codex, Code Llama, StarCoder, etc.), or a general-purpose model (such as GPT-4) for instruction fine-tuning.

[0168] The input file above can be constructed based on the prompt template, which is shown below:

[0169] "You are a code refactoring assistant. Please generate code based on the following AST structure and refactoring strategy:"

[0170] - AST structure: {ast_xml}

[0171] - Refactoring strategy: {strategy}

[0172] - Constraints: {constraints}

[0173] The generated code must conform to the {language} syntax specification and retain the external interface of the original code.

[0174] The large language model parses the AST, strategies, and constraints in the input file and selects a generation mode based on the AST node type (such as loop statements or function definitions). For example, for nodes marked "split function," multiple sub-functions are generated and their calling logic is adjusted. The large language model generates corresponding refactored code data based on the AST, strategies, and constraints in the input file.

[0175] After obtaining the refactored code data, you can check its validity using compilers or static analysis tools (such as Checkstyle and ESLint). You can also use Diff tools (such as Git Diff) to compare the old and new code, ensuring that only the target nodes have been modified and avoiding accidental changes. Furthermore, you can automatically generate refactoring comments based on the target refactoring strategy and update API documentation (such as Swagger descriptions) to make the final code clearer.

[0176] This invention accurately conveys code structure information through an Abstract Syntax Tree (AST), avoiding logical errors caused by lost context in traditional code generation and improving code generation accuracy. The target reconstruction strategy is explicitly encoded into the input file, constraining the generation direction of the large language model and preventing irrelevant code modifications. Combining structured AST with natural language strategy descriptions enhances the model's understanding of complex reconstruction tasks, further improving code generation accuracy.

[0177] like Figure 2 As shown, this embodiment of the invention provides an artificial intelligence-based software refactoring device, which includes:

[0178] The acquisition module 201 is used to acquire the current code data of the software to be refactored and the user data of the software to be refactored, wherein the user data is the interaction data of the user during the use of the software to be refactored;

[0179] Processing module 202 is used to determine the target refactoring strategy for the current code data based on the current code data and the user data;

[0180] The generation module 203 is used to generate the refactoring code data corresponding to the target refactoring strategy based on the large language model;

[0181] The refactoring module 204 is used to refactor the software to be refactored based on the refactoring code data, and the target software is obtained after the refactoring is completed.

[0182] Optionally, the processing module 202 is further configured to:

[0183] The current code data is subjected to code optimization detection, and a first refactoring strategy that can be optimized is determined from the current code data;

[0184] The user data is used to extract business expectations, thereby extracting the user's business expectations for the software to be refactored, and a second refactoring strategy is determined in the current code data based on the business expectations.

[0185] Based on the first refactoring strategy and the second refactoring strategy, the target refactoring strategy for the current code data is determined.

[0186] Optionally, the processing module 202 is further configured to:

[0187] The current code data is input into a pre-trained code optimization detection model for code optimization detection, and the code smells of the current code data are output.

[0188] Based on the code smells, an optimizable first refactoring strategy is determined from the current code data.

[0189] Optionally, the processing module 202 is further configured to:

[0190] Semantic extraction is performed on the user data to obtain multiple user semantics;

[0191] The user semantics are classified and processed to determine the user semantics related to the software to be reconstructed;

[0192] The user semantics related to the software to be reconstructed are used to generate user business expectations for the software to be reconstructed.

[0193] Optionally, the processing module 202 is further configured to:

[0194] The business expectation and the current code data are respectively parsed into multimodal feature vectors to obtain a first multimodal feature vector and a second multimodal feature vector. The first multimodal feature vector corresponds to the business expectation, and the second multimodal feature vector corresponds to the current code data.

[0195] Based on the vector similarity between the first multimodal feature vector and the second multimodal feature vector, a second reconstruction strategy is determined in the current code data.

[0196] Optionally, the processing module 202 is further configured to:

[0197] The common part between the first reconstruction strategy and the second reconstruction strategy is identified, and a first difference part that is different from the second reconstruction strategy is identified in the first reconstruction strategy, and a second difference part that is different from the first reconstruction strategy is identified in the second reconstruction strategy.

[0198] Perform a global verification on the first difference portion and the second difference portion to obtain the target difference portion that has been successfully verified globally.

[0199] The target difference portion and the common portion are determined as the target reconstruction strategy for the current code data.

[0200] Optionally, the generation module 203 is further configured to:

[0201] Obtain the Abstract Syntax Tree (AST) corresponding to the current code data;

[0202] Based on the target reconstruction strategy and the AST abstract syntax tree corresponding to the current code data, construct the input file of the large language model;

[0203] The input file is input into the large language model to generate the refactoring code data corresponding to the target refactoring strategy.

[0204] like Figure 3As shown, embodiments of the present invention also provide an electronic device, including a processor, which can execute any of the above-described artificial intelligence-based software refactoring methods.

[0205] Specifically, it includes processor 301 and memory 302, as well as a computer program stored in memory 302 and capable of running on processor 301, which executes an artificial intelligence-based software refactoring method, wherein:

[0206] The processor 301 executes the calculator program based on the artificial intelligence-based software refactoring method stored in the runtime memory 302, and performs the following steps:

[0207] Obtain the current code data and user data of the software to be refactored, wherein the user data is the interaction data of the user during the use of the software to be refactored;

[0208] Based on the current code data and the user data, a target refactoring strategy for the current code data is determined;

[0209] Based on the large language model, generate the refactoring code data corresponding to the target refactoring strategy;

[0210] Based on the reconstructed code data, the software to be reconstructed is reconstructed, and the target software is obtained after the reconstructing is completed.

[0211] Optionally, the process executed by processor 301 to determine the target refactoring strategy for the current code data based on the current code data and the user data includes:

[0212] The current code data is subjected to code optimization detection, and a first refactoring strategy that can be optimized is determined from the current code data;

[0213] The user data is used to extract business expectations, thereby extracting the user's business expectations for the software to be refactored, and a second refactoring strategy is determined in the current code data based on the business expectations.

[0214] Based on the first refactoring strategy and the second refactoring strategy, the target refactoring strategy for the current code data is determined.

[0215] Optionally, the process performed by processor 301 to perform code optimization detection on the current code data and determine an optimizable first refactoring strategy from the current code data includes:

[0216] The current code data is input into a pre-trained code optimization detection model for code optimization detection, and the code smells of the current code data are output.

[0217] Based on the code smells, an optimizable first refactoring strategy is determined from the current code data.

[0218] Optionally, the process of extracting business expectations from the user data performed by processor 301, extracting the user's business expectations for the software to be reconstructed, includes:

[0219] Semantic extraction is performed on the user data to obtain multiple user semantics;

[0220] The user semantics are classified and processed to determine the user semantics related to the software to be reconstructed;

[0221] The user semantics related to the software to be reconstructed are used to generate user business expectations for the software to be reconstructed.

[0222] Optionally, the process executed by processor 301 to determine a second refactoring strategy based on the business expectation in the current code data includes:

[0223] The business expectation and the current code data are respectively parsed into multimodal feature vectors to obtain a first multimodal feature vector and a second multimodal feature vector. The first multimodal feature vector corresponds to the business expectation, and the second multimodal feature vector corresponds to the current code data.

[0224] Based on the vector similarity between the first multimodal feature vector and the second multimodal feature vector, a second reconstruction strategy is determined in the current code data.

[0225] Optionally, the process executed by processor 301 to determine the target refactoring strategy for the current code data based on the first refactoring strategy and the second refactoring strategy includes:

[0226] The common part between the first reconstruction strategy and the second reconstruction strategy is identified, and a first difference part that is different from the second reconstruction strategy is identified in the first reconstruction strategy, and a second difference part that is different from the first reconstruction strategy is identified in the second reconstruction strategy.

[0227] Perform a global verification on the first difference portion and the second difference portion to obtain the target difference portion that has been successfully verified globally.

[0228] The target difference portion and the common portion are determined as the target reconstruction strategy for the current code data.

[0229] Optionally, the processor 301 executes the refactoring code data based on the large language model to generate the target refactoring strategy, including:

[0230] Obtain the Abstract Syntax Tree (AST) corresponding to the current code data;

[0231] Based on the target reconstruction strategy and the AST abstract syntax tree corresponding to the current code data, construct the input file of the large language model;

[0232] The input file is input into the large language model to generate the refactoring code data corresponding to the target refactoring strategy.

[0233] This invention also provides a computer-readable storage medium storing a computer program. When executed by a processor, the computer program implements the various processes of the AI-based software refactoring method provided in this invention and achieves the same technical effect. To avoid repetition, it will not be described again here.

[0234] Those skilled in the art will understand that all or part of the processes in the above embodiments can be implemented by a computer program instructing related hardware. The program can be stored in a computer-readable storage medium, and when executed, it can include the processes of the embodiments of the above methods. The storage medium can be a magnetic disk, optical disk, read-only memory (ROM), or random access memory (RAM), etc.

[0235] The above description discloses only preferred embodiments of the present invention and should not be construed as limiting the scope of the present invention. Therefore, equivalent variations made in accordance with the claims of the present invention are still within the scope of the present invention.

Claims

1. A software refactoring method based on artificial intelligence, characterized in that, The method includes the following steps: Obtain the current code data and user data of the software to be refactored, wherein the user data is the interaction data of the user during the use of the software to be refactored; Based on the current code data and the user data, a target refactoring strategy for the current code data is determined; Based on the large language model, generate the refactoring code data corresponding to the target refactoring strategy; Based on the reconstructed code data, the software to be reconstructed is reconstructed, and the target software is obtained after the reconstructing is completed. Based on the current code data and the user data, a target refactoring strategy for the current code data is determined, including: performing code optimization detection on the current code data, and determining an optimizable first refactoring strategy in the current code data; extracting business expectations from the user data, extracting the user's business expectations for the software to be refactored, and determining a second refactoring strategy in the current code data based on the business expectations; and determining a target refactoring strategy for the current code data based on the first refactoring strategy and the second refactoring strategy. Determining a second reconstruction strategy based on the business expectation in the current code data includes: parsing the business expectation and the current code data into multimodal feature vectors respectively to obtain a first multimodal feature vector and a second multimodal feature vector, wherein the first multimodal feature vector corresponds to the business expectation and the second multimodal feature vector corresponds to the current code data; and determining a second reconstruction strategy in the current code data based on the vector similarity between the first multimodal feature vector and the second multimodal feature vector.

2. The software refactoring method based on artificial intelligence as described in claim 1, characterized in that, The step of performing code optimization detection on the current code data and determining an optimizable first refactoring strategy from the current code data includes: The current code data is input into a pre-trained code optimization detection model for code optimization detection, and the code smells of the current code data are output. Based on the code smells, an optimizable first refactoring strategy is determined from the current code data.

3. The software refactoring method based on artificial intelligence as described in claim 1, characterized in that, The step of extracting business expectations from the user data to extract the user's business expectations for the software to be refactored includes: Semantic extraction is performed on the user data to obtain multiple user semantics; The user semantics are classified and processed to determine the user semantics related to the software to be reconstructed; The user semantics related to the software to be reconstructed are used to generate user business expectations for the software to be reconstructed.

4. The software refactoring method based on artificial intelligence as described in any one of claims 1 to 3, characterized in that, The step of determining the target refactoring strategy for the current code data based on the first refactoring strategy and the second refactoring strategy includes: The common part between the first reconstruction strategy and the second reconstruction strategy is identified, and a first difference part that is different from the second reconstruction strategy is identified in the first reconstruction strategy, and a second difference part that is different from the first reconstruction strategy is identified in the second reconstruction strategy. Perform a global verification on the first difference portion and the second difference portion to obtain the target difference portion that has been successfully verified globally. The target difference portion and the common portion are determined as the target reconstruction strategy for the current code data.

5. The software refactoring method based on artificial intelligence as described in any one of claims 1 to 3, characterized in that, The process of generating refactoring code data corresponding to the target refactoring strategy based on a large language model includes: Obtain the Abstract Syntax Tree (AST) corresponding to the current code data; Based on the target reconstruction strategy and the AST abstract syntax tree corresponding to the current code data, construct the input file of the large language model; The input file is input into the large language model to generate the refactoring code data corresponding to the target refactoring strategy.

6. A software reconfiguration device based on artificial intelligence, characterized in that, The AI-based software refactoring device includes: The acquisition module is used to acquire the current code data of the software to be refactored and the user data of the software to be refactored, wherein the user data is the interaction data of the user during the use of the software to be refactored; The processing module is used to determine the target refactoring strategy for the current code data based on the current code data and the user data. The generation module is used to generate refactoring code data corresponding to the target refactoring strategy based on the large language model; The refactoring module is used to refactor the software to be refactored based on the refactoring code data, and the target software is obtained after the refactoring is completed. Based on the current code data and the user data, a target refactoring strategy for the current code data is determined, including: performing code optimization detection on the current code data, and determining an optimizable first refactoring strategy in the current code data; extracting business expectations from the user data, extracting the user's business expectations for the software to be refactored, and determining a second refactoring strategy in the current code data based on the business expectations; and determining a target refactoring strategy for the current code data based on the first refactoring strategy and the second refactoring strategy. Determining a second reconstruction strategy based on the business expectation in the current code data includes: parsing the business expectation and the current code data into multimodal feature vectors respectively to obtain a first multimodal feature vector and a second multimodal feature vector, wherein the first multimodal feature vector corresponds to the business expectation and the second multimodal feature vector corresponds to the current code data; and determining a second reconstruction strategy in the current code data based on the vector similarity between the first multimodal feature vector and the second multimodal feature vector.

7. An electronic device, characterized in that, include: A memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor, when executing the computer program, implements the steps of the artificial intelligence-based software refactoring method as described in any one of claims 1 to 5.

8. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program that, when executed by a processor, implements the steps of the artificial intelligence-based software refactoring method as described in any one of claims 1 to 5.

Citation Information

Patent Citations

  • Code review method and device, electronic equipment and medium

    CN117648931A

  • Code modification strategy determination method and device, equipment, medium and program product

    CN119513709A