Target code generation method based on template engine
Through the target code generation method based on the template engine, the inefficiency and difficulty in maintaining code caused by manual code writing are solved, and the code quality and development efficiency are improved.
Patent Information
- Application Number
- CN202411646731.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-11-18
- Publication Date
- 2025-03-04
AI Technical Summary
During software development, manual code writing causes inefficiency, difficult code quality and difficult code maintenance, especially when dealing with repetitive code snippets.
The object code generation method based on the template engine is adopted, and the template engine is used to load and merge the data model to generate the object code by presetting the template files corresponding to the project.
It significantly reduces the workload of writing repetitive code repeatedly, improves development efficiency and code quality, unifies code style, simplifies code maintenance and team collaboration, reduces error rates, and supports rapid iteration and code reuse.
Smart Images

Figure CN119556897A_ABST
Abstract
Description
Technical Field
[0001] The invention belongs to the technical field of code generation, and in particular relates to a target code generation method based on a template engine. Background Art
[0002] In the field of computer software product development, traditional development methods usually rely on manual code writing. However, as the complexity of software systems continues to increase, developers face many challenges. Especially when dealing with highly repetitive code fragments, such as the framework code of the database access layer (DAO) and the business logic layer (Service), manually writing these codes is not only time-consuming and laborious, but also prone to various errors.
[0003] At present, most developers still use manual coding to develop software. The main problems caused by this method include: waste of time and energy due to repetitive work, inconsistent code style, easy introduction of various errors, difficulty in code maintenance, low code reusability and over-reliance on individual technical experts. These problems are particularly prominent in a fast-iteration development environment, which seriously affects development efficiency and code quality.
[0004] In addition, in a fast-iterative development environment, frequent changes in requirements often require adjustments to the code structure. Without the support of code generation tools, these adjustments need to be done manually, which is inefficient and error-prone. Different developers may write similar code in different ways, resulting in inconsistent code styles and increasing the difficulty of code maintenance and team collaboration. When writing code manually, developers may introduce errors for various reasons, which may be difficult to detect and cause various problems in the project later. Summary of the invention
[0005] The present invention provides a target code generation method based on a template engine to solve the problems of low efficiency, difficulty in maintaining code quality and difficulty in code maintenance caused by manual code writing when facing increasingly complex software development tasks.
[0006] The technical solution adopted by the present invention is:
[0007] A target code generation method based on a template engine, comprising:
[0008] S100: presetting a template file corresponding to the project;
[0009] The method further comprises:
[0010] S101: Loading the template file through a template engine, wherein the template file is generated according to the repetitive code of the project;
[0011] S102: merging the data model corresponding to the project with the template file to generate a target code;
[0012] The template file contains a tag for instructing the template engine to insert dynamic data into the repetitive code, and the data model contains the dynamic data required by the template file.
[0013] The target code generation method based on the template engine described in the present invention also includes the following additional technical features:
[0014] Pre-set the template files corresponding to the project, specifically:
[0015] Identifying the repetitive code from the project, and identifying the dynamic data required by the template file according to variables in the repetitive code;
[0016] Determining the type and target location of the target code to be generated;
[0017] The tag is defined in the repetitive code, and the repetitive code is called to generate the template file.
[0018] Identify the repetitive code from the project, specifically:
[0019] Acquire repetitive patterns and repetitive contents of the existing code of the project through static code analysis, and extract the repetitive contents from the existing code to generate the repetitive code;
[0020] and / or, obtaining repetitive patterns and repetitive contents of existing codes of the project through code similarity analysis, and extracting the repetitive contents from the existing codes to generate the repetitive codes;
[0021] and / or, obtaining repetitive patterns and repetitive contents of existing codes of the project through code coverage analysis, and extracting the repetitive contents from the existing codes to generate the repetitive code;
[0022] and / or, analyzing and obtaining the repetitive patterns and repetitive contents of the existing code of the project by means of code refactoring, and extracting the repetitive contents from the existing code to generate the repetitive code;
[0023] and / or, analyzing and obtaining the repetitive patterns and repetitive contents of the existing codes of the project by means of code pattern recognition, and extracting the repetitive contents from the existing codes to generate the repetitive codes;
[0024] The repetitive code is confirmed based on the length of the code block, the name of the variable method and the logic complexity; the types of the repetitive patterns include at least getter and setter methods, construction methods, exception handling logic, loops and conditional judgments, initialization methods and tool methods.
[0025] Extracting the repeated content from the existing code to generate the repetitive code is specifically:
[0026] Using a code analysis tool to count the number of times the code snippet in the existing code appears;
[0027] The code snippets whose number of times is greater than a specified threshold are regarded as the repeated content, and are formatted by a code formatting tool to form repetitive codes;
[0028] A custom annotation is added to the repetitive code, where the custom annotation is used to enable calling the repetitive code.
[0029] The tag is defined in the repetitive code, specifically:
[0030] Identify a filling position of the dynamic data in the repetitive code to generate a placeholder, wherein the placeholder is used to store the dynamic data;
[0031] The data model passed to the template file is determined according to the required dynamic data in the template file, and each dynamic data in the data model is matched with each placeholder in a one-to-one correspondence.
[0032] The data model corresponding to the project is merged with the template file to generate the target code, specifically:
[0033] Configuring the template engine;
[0034] The dynamic data in the data model is filled into the template file one by one through the template engine and the mark to generate the target code.
[0035] The dynamic data in the data model is filled into the template file one by one through the template engine and the mark to generate the target code, specifically:
[0036] According to the mark, the dynamic data replaces the mark and fills it into the template file one by one, and uses the replaced and filled template file as the target code;
[0037] Wherein, the template engine is provided with attribute information of the template file;
[0038] The type of the attribute information includes at least the path, encoding method, and log level of the template file.
[0039] The template file is generated based on the repetitive code of the project, specifically:
[0040] According to the project operation logic, determine the operation relationship between the repetitive codes and set the control structure;
[0041] Calling the repetitive code through the control structure to form the template file;
[0042] The control structure includes loop and conditional judgment logic.
[0043] The present invention further provides a computer-readable storage medium for storing computer instructions, wherein the computer instructions are used to enable a computer to execute the template engine-based target code generation method.
[0044] The present invention again provides an electronic device, comprising:
[0045] Memory, for storing computer instructions;
[0046] The processor is used to implement the template engine-based target code generation method when executing the computer instructions.
[0047] Due to the adoption of the above technical solution, the beneficial effects achieved by the present invention are as follows:
[0048] 1. In the present invention, a template file corresponding to a project is pre-set, and the template file is generated according to the repetitive code of the project. Developers only need to define the template file once to generate the required target code multiple times. This significantly reduces the workload of repeatedly writing repetitive code and greatly improves development efficiency. In this way, developers can focus on architecture design and core function implementation in the early stages of the project, and leave some repetitive code generation tasks to template tools. This not only improves development efficiency, but also makes the entire development process more efficient and orderly.
[0049] 2. In the present invention, different developers may have different programming habits, resulting in inconsistent code styles, which increases the difficulty of code maintenance and teamwork. The target code generation method based on the template engine can unify the code style and improve the consistency of the code. The template file generated according to the repetitive code makes the generated target code have a unified format and style. This means that even if the target code is generated by different developers, it will maintain a consistent appearance and internal logic, simplifying the subsequent code review and maintenance work. In addition, the template-based generation of target code can also eliminate the differences in code style caused by personal habits, making the code more standardized and normalized.
[0050] In large projects, it is particularly important to maintain consistency in code style, as this directly affects the readability and maintainability of the code. By using a target code generation method based on a template engine, the team can more easily maintain and expand the code base, while also making it easier for new members to quickly become familiar with the project structure.
[0051] 3. In the present invention, when manually writing code, the developer may introduce errors due to negligence, fatigue or other reasons. However, the target code generation method based on the template engine reduces the chance of human intervention, thereby reducing the error rate in the code. The definition of the template file and the data model ensures the quality of the generated code and avoids the non-standard problems that may occur when manually writing. Once an error is found, all related codes can be repaired by simply modifying the template file or the data model, which improves the efficiency of debugging and correction.
[0052] In addition, the generated code is not only of high quality, but also clearly structured, easy to maintain and expand. When the code needs to be modified or expanded, developers can quickly adjust it based on the template files and data models without having to write the code from scratch. This approach can also help the team find problems faster during the code review phase, because the generated code follows the predetermined templates and rules, making it easier to identify situations that do not meet expectations. This consistency also helps reduce subsequent maintenance costs, because code modifications can be more centralized and systematic.
[0053] 4. In the present invention, the rapid iteration development environment allows business requirements to change frequently. The method of generating code through the template engine can quickly adjust the template file and data model when the requirements change, and regenerate the code that meets the new requirements. This not only greatly improves the response speed of the development team, but also significantly reduces the development cost and time delay caused by changes in requirements.
[0054] In addition, the design of template files and data models supports the reuse of code snippets. By defining common template files and data models, developers can reuse verified code snippets and design patterns. When the project functionality needs to be expanded, new code can be quickly generated without having to write from scratch, further improving development efficiency and code maintainability. These technical means effectively improve the flexibility of the development team and the overall quality of the project.
[0055] 5. In the present invention, the method of generating code through the template engine reduces the dependence on individual technical experts and improves the overall ability and efficiency of the team. Team members can work together by jointly maintaining template files and data models, reducing the project's dependence on individual members. In addition, templated code generation simplifies the process of code review and integration and improves the efficiency of team collaboration. All team members can understand and use unified template files and data models, making team collaboration smoother and reducing errors caused by poor communication. This not only improves the development speed of the project, but also enhances the cohesion and overall combat effectiveness of the team.
[0056] With this approach, the team can better distribute tasks, and each member can focus on his or her expertise without having to worry about code consistency and maintainability. In addition, when a team member resigns or temporarily leaves, others can quickly take over his or her work because the code generation process is transparent and replicable, reducing the time and cost of knowledge transfer. This approach also promotes knowledge sharing and technology inheritance within the team, helps to cultivate more technical backbones, and thus further enhances the overall capabilities of the team and the sustainable development of the project. BRIEF DESCRIPTION OF THE DRAWINGS
[0057] The drawings described herein are used to provide a further understanding of the present invention and constitute a part of the present invention. The exemplary embodiments of the present invention and their descriptions are used to explain the present invention and do not constitute an improper limitation of the present invention. In the drawings:
[0058] Figure 1 The figure is a flow chart of the target code generation method based on the template engine in one embodiment of the present invention. DETAILED DESCRIPTION
[0059] In order to more clearly illustrate the overall concept of the present invention, a detailed description is given below in an exemplary manner in conjunction with the accompanying drawings.
[0060] In the following description, many specific details are set forth to facilitate a full understanding of the present invention. However, the present invention may also be implemented in other ways different from those described herein. Therefore, the protection scope of the present invention is not limited to the specific embodiments disclosed below.
[0061] like Figure 1 As shown, a target code generation method based on a template engine, the method comprising:
[0062] S100: Pre-set a template file corresponding to the project.
[0063] It should be noted that the template file in this step refers to the file used to define the code structure and content during the code generation process. These files usually contain static text and dynamic tags, where the static text part is a fixed code fragment, and the dynamic tag is used to instruct the template engine to insert specific dynamic data when generating code.
[0064] This step is to prepare for the target code generation method based on the template engine, and provide the necessary files for engine calling and dynamic data insertion. By pre-configuring the template files, it can be ensured that during the code generation process, the template engine can accurately load and parse these files, thereby efficiently generating code that meets the project requirements.
[0065] Specifically, before the project starts, the corresponding template files are created and configured according to the project's requirements and characteristics. These template files define the structure and static parts of the code, as well as the insertion points of dynamic data. These template files will be loaded and parsed by the template engine to generate the final code. The dynamic tags contained in the template files will guide the template engine to insert specific dynamic data when generating code.
[0066] This step is the initial stage of the entire code generation process, and its purpose is to prepare for subsequent code generation.
[0067] The target code generation method based on the template engine also includes:
[0068] S101: Loading the template file through a template engine, wherein the template file is generated according to the repetitive code of the project.
[0069] It should be noted that a template engine is a tool or library that combines static template files with dynamic data models to generate final output files. These output files can be HTML pages, configuration files, source code, etc. The main function of a template engine is to insert dynamic data into template files and generate output content that conforms to a specific format and structure.
[0070] Specifically, the template engine first parses the template file and identifies the static text and dynamic tags in it. The static text part remains unchanged, and the dynamic tags are used to instruct the engine where to insert dynamic data.
[0071] The template engine binds the data in the data model to the dynamic tags in the template file. The data model is usually a structure containing key-value pairs (such as a dictionary, object, etc.), and the engine obtains the corresponding value from the data model according to the variable name in the tag.
[0072] After the binding is completed, the template engine will generate the final output file. The generated file can be saved to disk, output to the console, or directly returned to the application for use.
[0073] Common template engines include Velocity, FreeMarker, Thymeleaf, Jinja2, Handlebars, etc. Among them:
[0074] Velocity is a Java-based template engine that is widely used to generate text content such as HTML, XML, SQL, etc. Velocity Template Language (VTL) is simple and easy to use, and supports syntax such as variables, conditional judgments, and loops.
[0075] FreeMarker is another Java-based template engine, commonly used in Web application development. FreeMarker provides a rich set of template instructions and a flexible data binding mechanism.
[0076] Thymeleaf is a modern server-side Java template engine, mainly used for web application development. Thymeleaf supports HTML5 syntax and can preview template files directly in the browser.
[0077] Jinja2 is a Python-based template engine that is widely used in web frameworks such as Flask and Django. Jinja2 provides powerful template inheritance and macro functions.
[0078] Handlebars is a template engine based on JavaScript that supports both client and server. Handlebars has a concise syntax and is easy to learn and use.
[0079] The template file is generated according to the repetitive code of the project. In the process of software development, a large amount of repetitive code is often encountered. These codes are usually code fragments with similar structures and similar contents, such as the code of the database access layer (DAO), the framework code of the business logic layer (Service), etc. Manually writing these repetitive codes is not only time-consuming, but also prone to errors.
[0080] In this application, the template file is generated according to the repetitive code of the project, which is the key to achieve repetitive code reuse. Through the reuse of repetitive code, the workload of repeatedly writing similar codes can be significantly reduced, and development efficiency can be improved. This not only reduces duplication of work, but also ensures that the generated code is consistent, improving code quality and maintainability.
[0081] In this step, the template file is loaded through the template engine, and the template is parsed to identify the static text and dynamic tags therein. The static text part remains unchanged, and the dynamic tags are used to indicate where the engine inserts dynamic data. This lays the foundation for merging the data model with the template file to generate the target code.
[0082] S102: merging the data model corresponding to the project with the template file to generate a target code;
[0083] The template file contains a tag for instructing the template engine to insert dynamic data into the repetitive code, and the data model contains the dynamic data required by the template file.
[0084] It should be noted that the data model is a structured representation for storing and organizing data. In the code generation process based on the template engine, the data model contains the dynamic data required in the template file. This data is usually stored in the form of key-value pairs, which can be simple dictionaries, complex objects, lists, etc. The role of the data model is to provide specific values for the template engine so that it can be inserted into the corresponding position of the template file when generating code.
[0085] The data model includes key-value pairs. The most basic unit in the data model is the key-value pair, where the key is an identifier and the value is the specific data to be inserted into the template; of course, the data model can contain more complex structures, such as lists, objects, nested structures, etc. The data in the data model can come from a variety of sources, such as databases, configuration files, user input, etc.
[0086] The data model provides specific values for the tags in the template file, ensuring that the generated code meets the project requirements. Moreover, the flexibility of the data model enables different codes to be generated according to different requirements. By adjusting the values in the data model, different code variants can be generated.
[0087] The template file contains a tag for instructing the template engine to insert dynamic data into the repetitive code. The template engine is instructed to insert actual dynamic data when generating code through specific tags. These tags are usually defined using the specific syntax of the template engine, such as Velocity Template Language (VTL), FreeMarker, Thymeleaf, etc. The design of the tag improves the accuracy of dynamic data insertion into the repetitive code and clarifies the mapping relationship between the data model and the template file.
[0088] In this step, the data model corresponding to the project is merged with the template file to generate the target code. The template engine matches and merges the dynamic data in the data model with the tags in the template file. The tags in the template file will be replaced by the actual values in the data model. The result of the merger is the final target code, which can be saved to a file, output to the console, or directly returned to the application for use.
[0089] In this step, the template file and the data model are set separately. The template file is generated according to the repetitive code of the project. The data model contains the dynamic data required by the template file. That is, the specific data in the target code is generated separately from the repetitive code. By setting the mapping relationship between the dynamic data and the repetitive code, the template file and the data model are combined through the mapping relationship to generate the target code.
[0090] Therefore, through the combination of template files and data models, a large amount of similar code can be quickly generated, reducing the duplication of developers and improving development efficiency. The generated code is consistent, avoiding the subtle differences that may occur when manually writing code, and reducing spelling errors, syntax errors and other problems caused by manually writing code. This ensures that the generated code meets project specifications and standards and improves the quality of the code.
[0091] When project requirements change, you only need to adjust the data model to quickly generate new code, supporting rapid iteration and development of the project. The separation of template files and data models makes the code generation process more modular and easy to maintain and expand. When the code structure needs to be modified, you only need to adjust the template file without modifying a large amount of code, which makes the code generation process more flexible and able to cope with changing project environments.
[0092] The use of template files and data models standardizes the code generation process, making it easier for team members to understand and use the generated code, improving the efficiency of team collaboration. Template files and data models can be used as shared resources, and team members can jointly maintain and improve them, promoting the sharing and accumulation of knowledge.
[0093] As a preferred implementation of the present invention, a template file corresponding to the project is pre-set, specifically:
[0094] Identifying the repetitive code from the project, and identifying the dynamic data required by the template file according to variables in the repetitive code;
[0095] Determining the type and target location of the target code to be generated;
[0096] The tag is defined in the repetitive code, and the repetitive code is called to generate the template file.
[0097] This step aims to obtain the template file and the dynamic data required by the template file based on the repetitive code, and to clarify the target code generation requirements, such as the type and target location of the target code to be generated, so that the generated template file meets the user's needs.
[0098] Identifying repetitive code mainly refers to identifying similar code snippets that appear frequently in a project, such as database add, delete, query, and modify operations, user information verification logic, etc. These code snippets often have similar structures and logic, but the specific implementation details may be different. The identification of repetitive code mainly includes finding out the code patterns that are repeatedly used in the project through code review, static analysis tools, etc. These patterns are usually the implementation of basic functions, such as data access, business logic processing, etc.
[0099] Variables in repetitive code mainly refer to the dynamically changing parts extracted from the identified repetitive code, such as table names, field names, class names, etc. These variables will become part of the data model and are used to insert dynamic data in the template file. Through code analysis, determine which parts are fixed and which parts are dynamically changing. The dynamically changing parts will be extracted to form key-value pairs in the data model.
[0100] Defining tags in template files mainly refers to defining tags used to insert dynamic data in template files, such as variable tags. These tags instruct the template engine to insert actual dynamic data when generating code. You can define corresponding tags based on the extracted variables.
[0101] Determine the type and location of the target code The main purpose is to clarify the type (such as DAO class, Service class, Controller class, etc.) and storage location (such as a specific directory or file) of the generated target code. This helps ensure that the generated code can be correctly integrated into the project. In this step, you can determine the type and storage location of the generated code based on the project's requirements and architecture.
[0102] Calling repetitive code to generate template file mainly refers to generating template file by calling identified repetitive code. The template file will contain static part and dynamic markup, which is used to generate final target code.
[0103] In this step, by clarifying the type of generated code, you can ensure that the generated code meets the requirements and architecture of the project. By clarifying the storage location of the generated code, you can ensure that the generated code can be correctly placed in the project directory structure, which helps keep the project clean and orderly. Clear code types and storage locations make the project's directory structure clearer, easier for other developers to understand and maintain, and can prevent the generated code from overwriting existing files, reducing potential errors and conflicts. It can also ensure that the generated file path is correct and avoid compilation or runtime problems caused by path errors. The generated code can be correctly integrated into the project, reducing debugging time caused by code location errors and improving development efficiency.
[0104] As a preferred embodiment of this implementation, identifying the repetitive code from the project is specifically:
[0105] Acquire repetitive patterns and repetitive contents of the existing code of the project through static code analysis, and extract the repetitive contents from the existing code to generate the repetitive code;
[0106] and / or, obtaining repetitive patterns and repetitive contents of existing codes of the project through code similarity analysis, and extracting the repetitive contents from the existing codes to generate the repetitive codes;
[0107] and / or, obtaining repetitive patterns and repetitive contents of existing codes of the project through code coverage analysis, and extracting the repetitive contents from the existing codes to generate the repetitive code;
[0108] and / or, analyzing and obtaining the repetitive patterns and repetitive contents of the existing code of the project by means of code refactoring, and extracting the repetitive contents from the existing code to generate the repetitive code;
[0109] and / or, analyzing and obtaining the repetitive patterns and repetitive contents of the existing codes of the project by means of code pattern recognition, and extracting the repetitive contents from the existing codes to generate the repetitive codes;
[0110] The repetitive code is confirmed based on the length of the code block, the name of the variable method and the logic complexity; the types of the repetitive patterns include at least getter and setter methods, construction methods, exception handling logic, loops and conditional judgments, initialization methods and tool methods.
[0111] Embodiment 1: Obtain the repetitive patterns and repetitive contents of the existing code of the project through static code analysis, and extract the repetitive contents from the existing code to generate the repetitive code.
[0112] Static code analysis is to find repeated patterns and duplicate content in the code by analyzing the structure, syntax and logic of the code without executing the code. Common static code analysis tools include SonarQube, PMD, Checkstyle, FindBugs, etc. These tools can help developers identify repeated patterns and duplicate content in the code.
[0113] Specifically, static code analysis tools are used to scan the code in the project and identify frequently occurring similar code snippets. These snippets usually have similar structures and logics, but the specific implementation details may be different.
[0114] Then, specific code snippets are extracted from the identified repetitive patterns, which will become the basis for generating repetitive codes.
[0115] Abstract the extracted repetitive content into common repetitive codes. These repetitive codes can be functions, classes, methods, etc., which are used to handle common logic and operations.
[0116] Embodiment 2: The repetitive patterns and repetitive contents of the existing codes of the project are obtained through code similarity analysis, and the repetitive contents are extracted from the existing codes to generate the repetitive codes.
[0117] Code similarity analysis is a technique that compares the structure, syntax, and logic of the code to identify similar or repeated code snippets. This analysis can help developers find redundant parts in the code and optimize it. Common code similarity analysis tools include Simian, CloneDR, CPatMiner, etc. These tools can calculate the similarity between code snippets through algorithms and identify repeated patterns.
[0118] Specifically, code similarity analysis tools are used to scan the code in the project and identify frequently occurring similar code snippets. These snippets usually have similar structures and logics, but the specific implementation details may be different.
[0119] From the identified repetitive patterns, specific code snippets are extracted. These code snippets will become the basis for generating repetitive code.
[0120] Abstract the extracted repetitive content into common code templates. These templates can be functions, classes, methods, etc., which are used to handle common logic and operations.
[0121] Embodiment 3: The repetitive patterns and repetitive contents of the existing codes of the project are obtained through code coverage analysis, and the repetitive contents are extracted from the existing codes to generate the repetitive codes.
[0122] Code coverage analysis is a technique for evaluating the degree of code coverage by test cases. By running test cases, recording which lines of code are executed and which are not executed, the adequacy of the test is evaluated. Common code coverage analysis tools include JaCoCo, Cobertura, Clover, etc. These tools can generate detailed reports showing which lines of code are covered by tests and which are not.
[0123] Specifically, the code coverage analysis tool is used to scan the code in the project and identify frequently occurring similar code snippets. These snippets usually have similar structures and logics, but the specific implementation details may be different.
[0124] From the identified repetitive patterns, specific code snippets are extracted. These code snippets will become the basis for generating repetitive code.
[0125] Abstract the extracted repetitive content into common code templates. These templates can be functions, classes, methods, etc., which are used to handle common logic and operations.
[0126] Embodiment 4: Analyze and obtain the repetitive patterns and repetitive contents of the existing code of the project by means of code refactoring, and extract the repetitive contents from the existing code to generate the repetitive code.
[0127] Code refactoring refers to the structural adjustment and optimization of code without changing the external behavior of the code to improve the readability, maintainability and extensibility of the code. Through code refactoring, you can identify and eliminate repeated patterns in the code, extract common logic, and generate more concise and efficient code.
[0128] Specifically, through the code refactoring process, frequently occurring similar code snippets are identified manually or using tools. These snippets usually have similar structure and logic, but the specific implementation details may be different.
[0129] From the identified repetitive patterns, specific code snippets are extracted. These code snippets will become the basis for generating repetitive code.
[0130] Abstract the extracted repetitive content into common code templates. These templates can be functions, classes, methods, etc., which are used to handle common logic and operations.
[0131] Embodiment 5: Analyze and obtain the repetitive patterns and repetitive contents of the existing code of the project by means of code pattern recognition, and extract the repetitive contents from the existing code to generate the repetitive code.
[0132] Code pattern recognition is a technology that automatically identifies common patterns and repeated content in the code by analyzing the structure, syntax, and logic of the code. This technology can help developers find redundant parts in the code and optimize it. Common code pattern recognition tools include RIPS, Fortify, SonarQube, etc. These tools can automatically identify repeated patterns in the code through algorithms.
[0133] Specifically, code pattern recognition tools are used to scan the code in the project and automatically identify frequently occurring similar code snippets. These snippets usually have similar structures and logics, but the specific implementation details may be different.
[0134] From the identified repetitive patterns, specific code snippets are extracted. These code snippets will become the basis for generating repetitive code.
[0135] Abstract the extracted repetitive content into common code templates. These templates can be functions, classes, methods, etc., which are used to handle common logic and operations.
[0136] In this step, the repetitive code is confirmed based on the length of the code block, the name of the variable method and the logic complexity; the types of the repetitive patterns include at least getter and setter methods, construction methods, exception handling logic, loops and conditional judgments, initialization methods, and tool methods.
[0137] Specifically, in confirming repetitive code, the length of the code block is used to determine whether it is repeated content. If a long code block appears in multiple places, it is likely to be repeated. For example, if a code block with more than 10 lines appears in multiple places, it is likely to be repeated.
[0138] Determine whether the code is duplicated by the similarity of variable and method names. The same variable and method names usually mean similar logic. For example, the same variable and method names usually mean similar logic.
[0139] Determine whether the code is repeated by logic complexity. If complex logic appears in multiple places, it may need to be abstracted into a public method or class. For example, if a complex try-catch statement appears in multiple places, it may need to be abstracted into a public method or class.
[0140] In the type of repeated pattern, Getter and Setter methods are access methods of attributes, which are usually used to encapsulate the internal state of the class;
[0141] The constructor is a method used to initialize an object;
[0142] Exception handling logic refers to the code block that handles exceptions, usually including try-catch statements;
[0143] Loops and conditionals refer to code blocks used to traverse data structures and conditional branches;
[0144] Initialization method refers to the method used to initialize objects or resources;
[0145] Tool methods refer to common auxiliary methods, such as string processing, date conversion, etc.
[0146] In this step, by abstracting the common logic, the generated repetitive code is consistent, avoiding the subtle differences that may occur when manually writing the code. It can also reduce spelling errors, grammatical errors and other problems caused by manually writing the code, thereby improving the quality of the code.
[0147] By organizing and reusing repetitive codes, the workload of developers manually writing similar codes is reduced, and development efficiency is improved. When project requirements change, new codes can be quickly generated by simply adjusting the data model, supporting rapid iteration and development of projects.
[0148] Specifically, extracting the repeated content from the existing code to generate the repetitive code is specifically as follows:
[0149] Using a code analysis tool to count the number of times the code snippet in the existing code appears;
[0150] The code snippets whose number of times is greater than a specified threshold are regarded as the repeated content, and are formatted by a code formatting tool to form repetitive codes;
[0151] A custom annotation is added to the repetitive code, where the custom annotation is used to enable calling the repetitive code.
[0152] It should be noted that code analysis tools include SonarQube, PMD, FindBugs, etc. These tools can scan the code and identify frequently occurring code snippets. Before performing the analysis, you need to configure the tool's rule set, focusing on code duplication detection.
[0153] Code formatting tools include IntelliJ IDEA, Eclipse, Prettier, etc. These tools can automatically format the code to ensure consistent code style.
[0154] Specifically, use code analysis tools to count the number of code snippets:
[0155] Select a tool, such as SonarQube; configure the tool, configure SonarQube's rule set, focus on code duplication detection; run analysis, run SonarQube, scan the code in the project, and generate a report.
[0156] Count the number of code snippets:
[0157] Extract code snippets and extract frequently occurring code snippets from the reports generated by SonarQube;
[0158] Count the number of times each code snippet appears in the project.
[0159] Identify duplicate content:
[0160] Set a threshold, for example, 5 times. Code snippets that appear more than 5 times are considered duplicates.
[0161] Manual review, manually review the identified duplicate content to confirm that it is indeed a duplicate.
[0162] Format the code using the code formatting tool:
[0163] Select a tool, for example, IntelliJ IDEA;
[0164] Format the code. Format the extracted duplicate content through the code formatting function of IntelliJ IDEA to form a unified code style.
[0165] Generate reproducible code:
[0166] Abstract common logic and abstract formatted repetitive content into common code templates. For example, abstract database add, delete, query and modify operations into common methods.
[0167] Add custom annotations to repetitive code:
[0168] Define a custom annotation to mark repetitive code so that it can be called;
[0169] Apply annotations: Add custom annotations to generated repetitive code so that you can call these codes where needed.
[0170] As another example under this implementation mode, the tag is defined in the repetitive code, specifically:
[0171] Identify a filling position of the dynamic data in the repetitive code to generate a placeholder, wherein the placeholder is used to store the dynamic data;
[0172] The data model passed to the template file is determined according to the required dynamic data in the template file, and each dynamic data in the data model is matched with each placeholder in a one-to-one correspondence.
[0173] In this step, the placeholder is usually a special marker that instructs the template engine to insert actual dynamic data when generating code. Common placeholder formats include ${variableName}, #variableName, etc.
[0174] Specifically, identify the filling position of dynamic data:
[0175] Define placeholders. In the template file, define placeholders for storing dynamic data. For example, use ${tableName} to represent the table name and ${fieldName} to represent the field name.
[0176] Select the placeholder format. Common placeholder formats include ${variableName}, #variableName, etc.
[0177] Determine the data model:
[0178] Analyze the template files and the placeholders in the template files to determine the required dynamic data, such as className, tableName, fields, values, setFields, id, etc.
[0179] Create a data model. Create a data model based on the required dynamic data. The data model contains key-value pairs of dynamic data, which are used to insert specific values in the template file.
[0180] This step provides a mapping relationship between the template file and the data model through the design of placeholders, indicating the filling method of filling the template file with dynamic data from the data model when the data model corresponding to the project is merged with the template file.
[0181] Placeholders allow you to flexibly insert dynamic data into template files. This means that template files can adapt to a variety of different scenarios and requirements without having to write a separate template for each situation. When project requirements change, you only need to adjust the data in the data model to generate new code without modifying the template file itself. This greatly improves the flexibility and adaptability of code generation. The determination of mapping relationships and filling logic standardizes the code generation process, making it easier for team members to understand and use the generated code, improving the efficiency of team collaboration.
[0182] The template file defines the basic structure and logic of the code, ensuring that the generated code follows a unified standard and is easy for team members to understand and maintain. The template file defines the basic structure of the code, making the generated code have clear logic and structure, and easy to read and understand.
[0183] As a preferred implementation of the present invention, the data model corresponding to the project is merged with the template file to generate the target code, specifically:
[0184] Configuring the template engine;
[0185] The dynamic data in the data model is filled into the template file one by one through the template engine and the mark to generate the target code.
[0186] This step aims to fill the dynamic data in the data model into the template file one by one through the template engine to generate the target code.
[0187] Specifically, configure the template engine:
[0188] Choose a template engine, choose a suitable template engine, such as Velocity, FreeMarker, Thymeleaf, etc.;
[0189] Install and configure according to the documentation of the selected template engine, for example, use Maven to add dependencies.
[0190] Load the template file:
[0191] The template engine loads the template file according to the configured path, analyzes the placeholders in the template file, and determines the required dynamic data. Analyzes the placeholders in the template file and determines the required dynamic data. For example, className, tableName, fields, values, setFields, id, etc.
[0192] Create the context:
[0193] Create a context object, pass the data model to the template engine, and create a context object. The context object is used to store dynamic data for the template engine to use when generating code.
[0194] Generate target code:
[0195] Merge data model and template file: The template engine matches and merges the data in the data model with the placeholders in the template file;
[0196] Generate target code: The result of the merger is the final target code, which can be saved to a file, output to the console, or directly returned to the application for use.
[0197] As a preferred embodiment of this implementation, the dynamic data in the data model is filled into the template file one by one through the template engine and the mark to generate the target code, specifically:
[0198] According to the mark, the dynamic data replaces the mark and fills it into the template file one by one, and uses the replaced and filled template file as the target code;
[0199] Wherein, the template engine is provided with attribute information of the template file;
[0200] The type of the attribute information includes at least the path, encoding method, and log level of the template file.
[0201] In this step, the attribute information of the template file includes:
[0202] Path, used to specify the path of the template file;
[0203] Encoding mode, used to specify the encoding mode of the template file, such as UTF-8;
[0204] Log level, used to set the log level of the template engine, such as DEBUG, INFO, etc.
[0205] In addition, the template engine matches and replaces the data in the data model with the placeholders in the template file; fills the replaced data into the template file to generate the final target code; saves the generated target code to a file, outputs it to the console, or directly returns it to the application for use.
[0206] In this step, by setting the path, encoding method, and log level of the template file in the template engine, the flexibility and maintainability of the configuration can be significantly improved. Centralized management of these attribute information facilitates management and maintenance. If you need to change the attribute, you only need to modify one configuration. This method makes it easy to adjust the configuration for different projects or environments, avoid hard-coded paths, reduce path errors, and improve code robustness. Setting the encoding method (such as UTF-8) ensures that there is no garbled code when reading and writing files, and unifies the encoding standard. Setting the log level (such as DEBUG, INFO) facilitates debugging and monitoring, while optimizing performance. Centralized configuration makes the code clearer and easier to read, and adding comments and documentation further improves understandability. Standardized configuration reduces problems in team collaboration, and configuration files as shared resources promote knowledge accumulation. Use environment variables for easy deployment, and integrate into the CI / CD process to improve automation and deployment efficiency.
[0207] As a preferred implementation of the present invention, the template file is generated according to the repetitive code of the project, specifically:
[0208] According to the project operation logic, determine the operation relationship between the repetitive codes and set the control structure;
[0209] Calling the repetitive code through the control structure to form the template file;
[0210] The control structure includes loop and conditional judgment logic.
[0211] During project development, we often encounter some repetitive code logic, which can be managed and generated through control structures (such as loops and conditional judgments).
[0212] Loop structure: If you need to generate multiple similar code blocks, you can use a loop structure. For example, when generating multiple DAO classes, you can use a loop to traverse the information of each class and generate the corresponding code.
[0213] Conditional logic: If the generation conditions of certain code blocks are different, you can use conditional logic. For example, based on the characteristics of the database table (such as whether there is an auto-increment primary key), decide whether to generate certain specific codes.
[0214] Call repetitive code: In the template file, use the control structure to call the repetitive code. Through the control structure, the final template file is generated according to different conditions and loop times.
[0215] This step realizes the calling and connection of repetitive codes through the control structure to form a template file.
[0216] The present invention also provides a computer-readable storage medium, which is used to store computer instructions, and the computer instructions are used to enable a computer to execute and implement a method for generating a target code based on a template engine. Therefore, any technical effect of the above-mentioned method for generating a target code based on a template engine can be achieved, which will not be repeated here.
[0217] The present invention again provides an electronic device, comprising:
[0218] Memory, for storing computer instructions;
[0219] The processor is used to implement the above-mentioned method for generating target code based on the template engine when executing the computer instruction. Therefore, any technical effect of the above-mentioned method for generating target code based on the template engine can be achieved, which will not be repeated here.
[0220] Anything not described in the present invention can be achieved by adopting or drawing on existing technologies.
[0221] The various embodiments in this specification are described in a progressive manner, and the same or similar parts between the various embodiments can be referenced to each other, and each embodiment focuses on the differences from other embodiments.
[0222] The above description is only an embodiment of the present invention and is not intended to limit the present invention. For those skilled in the art, the present invention may have various modifications and variations. Any modification, equivalent substitution, improvement, etc. made within the spirit and principle of the present invention should be included in the scope of the claims of the present invention.
Claims
1. A target code generation method based on a template engine, characterized in that: Presetting a template file corresponding to the project, the method further includes: Loading the template file through a template engine, wherein the template file is generated according to the repetitive code of the project; The data model corresponding to the project is merged with the template file to generate the target code; the template file contains a mark for instructing the template engine to insert dynamic data into the repetitive code, and the data model contains the dynamic data required by the template file.
2. The method according to claim 1, characterized in that Pre-set the template files corresponding to the project, specifically: Identifying the repetitive code from the project, and identifying the dynamic data required by the template file according to variables in the repetitive code; Determining the type and target location of the target code to be generated; The tag is defined in the repetitive code, and the repetitive code is called to generate the template file.
3. The method according to claim 2, characterized in that Identify the repetitive code from the project, specifically: Acquire repetitive patterns and repetitive contents of the existing code of the project through static code analysis, and extract the repetitive contents from the existing code to generate the repetitive code; and / or, obtaining repetitive patterns and repetitive contents of existing codes of the project through code similarity analysis, and extracting the repetitive contents from the existing codes to generate the repetitive codes; and / or, obtaining repetitive patterns and repetitive contents of existing codes of the project through code coverage analysis, and extracting the repetitive contents from the existing codes to generate the repetitive code; and / or, analyzing and obtaining the repetitive patterns and repetitive contents of the existing code of the project by means of code refactoring, and extracting the repetitive contents from the existing code to generate the repetitive code; and / or, analyzing and obtaining the repetitive patterns and repetitive contents of the existing codes of the project by means of code pattern recognition, and extracting the repetitive contents from the existing codes to generate the repetitive codes; Among them, the repetitive code is confirmed based on the length of the code block, the name of the variable method and the logic complexity; the types of the repetitive pattern include at least getter and setter methods, construction methods, exception handling logic, loops and conditional judgments, initialization methods, and tool methods.
4. The method according to claim 3, characterized in that Extracting the repeated content from the existing code to generate the repetitive code is specifically: Using a code analysis tool to count the number of times the code snippet in the existing code appears; The code snippets whose number of times is greater than a specified threshold are regarded as the repeated content, and are formatted by a code formatting tool to form repetitive codes; A custom annotation is added to the repetitive code, where the custom annotation is used to enable calling the repetitive code.
5. The method according to claim 2, characterized in that The tag is defined in the repetitive code, specifically: Identify a filling position of the dynamic data in the repetitive code to generate a placeholder, wherein the placeholder is used to store the dynamic data; The data model passed to the template file is determined according to the required dynamic data in the template file, and each dynamic data in the data model is matched with each placeholder in a one-to-one correspondence.
6. The method according to claim 1, characterized in that The data model corresponding to the project is merged with the template file to generate the target code, specifically: Configuring the template engine; The dynamic data in the data model is filled into the template file one by one through the template engine and the mark to generate the target code.
7. The method according to claim 6, characterized in that The dynamic data in the data model is filled into the template file one by one through the template engine and the mark to generate the target code, specifically: According to the mark, the dynamic data replaces the mark and fills it into the template file one by one, and uses the replaced and filled template file as the target code; Wherein, the template engine is provided with attribute information of the template file; The type of the attribute information includes at least the path, encoding method, and log level of the template file.
8. The method according to claim 1, characterized in that The template file is generated based on the repetitive code of the project, specifically: According to the project operation logic, determine the operation relationship between the repetitive codes and set the control structure; Calling the repetitive code through the control structure to form the template file; The control structure includes loop and conditional judgment logic.
9. A computer-readable storage medium, characterized in that: The computer-readable storage medium is used to store computer instructions, and the computer instructions are used to enable a computer to execute the template engine-based target code generation method described in any one of claims 1 to 8.
10. An electronic device, characterized in that: include: Memory, for storing computer instructions; A processor, used to implement the template engine-based target code generation method as described in any one of claims 1 to 8 when executing the computer instructions.
Citation Information
Patent Citations
Method and device for generating program codes of software
CN104267967A
Code generation method and device based on integration of frameworks Spring and MyBatis
CN107391153A
Method and device for generating a program code file, and an electronic device
CN109491652A
Code framework generation method and device, equipment and storage medium
CN116841532A
Java universal code generation optimization method and system
CN116991390A
Cited By
Code generation method and system based on dynamic template engine
CN120929071A