Disclosure of Invention
The invention provides a target code generation method based on a template engine, which aims to solve the problems of low efficiency, difficulty in maintaining code quality, difficulty in maintaining code and the like caused by manually writing the code when facing increasingly complex software development tasks.
The technical scheme adopted by the invention is as follows:
A template engine-based object code generation method, comprising:
S100, presetting a template file corresponding to an item;
the method further comprises the steps of:
S101, loading the template file through a template engine, wherein the template file is generated according to the repetitive codes of the items;
S102, merging the data model corresponding to the project with the template file to generate target codes;
the template file contains a marker for instructing the template engine to insert dynamic data in the repetitive code, and the data model contains the dynamic data required by the template file.
The object code generating method based on the template engine in the invention further comprises the following additional technical characteristics:
Presetting a template file corresponding to an item, wherein the template file comprises the following specific steps:
Identifying the repeatability code from the item, and identifying the dynamic data required by the template file according to variables in the repeatability code;
Determining the type and the target position of the target code to be generated;
defining the mark in the repetitive code, and calling the repetitive code to generate the template file.
Identifying the repeatability code from the item, specifically:
Acquiring a repeated pattern and repeated content of an existing code of the item through static code analysis, and extracting the repeated content from the existing code to generate the repeated code;
And/or, obtaining a repeated pattern and repeated content of an existing code of the item through code similarity analysis, and extracting the repeated content from the existing code to generate the repeated code;
and/or, obtaining a repeated pattern and repeated content of an existing code of the item through code coverage analysis, and extracting the repeated content from the existing code to generate the repeated code;
And/or analyzing and acquiring a repeated pattern and repeated content of an existing code of the project through a code reconstruction mode, and extracting the repeated content from the existing code to generate the repeated code;
and/or analyzing and acquiring a repeated pattern and repeated content of an existing code of the project through a code pattern recognition mode, and extracting the repeated content from the existing code to generate the repeated code;
The type of the repeated pattern at least comprises getter and setter methods, a construction method, exception handling logic, loop and condition judgment, an initialization method and a tool method.
Extracting the repeated content from the existing code to generate the repeated code, specifically:
counting the number of times of occurrence of the code segments in the existing code by using a code analysis tool;
Taking the code segments with the times larger than a specified threshold value as the repeated content, and carrying out code formatting through a code formatting tool to form a repeated code;
And adding a custom annotation to the repeatability code, wherein the custom annotation is used for enabling calling of the repeatability code.
Defining the mark in the repetitive code, specifically:
Identifying a fill location of the dynamic data in the repetitive code to generate a placeholder, the placeholder for storing the dynamic data;
And determining the data model transmitted to the template file according to the required dynamic data in the template file, wherein each dynamic data in the data model is matched with each placeholder in a one-to-one correspondence manner.
Merging the data model corresponding to the item with the template file to generate an object code, specifically:
Configuring the template engine;
and filling dynamic data in the data model into the template file in a one-to-one correspondence manner through the template engine and the mark so as to generate the target code.
Filling dynamic data in the data model into the template file in a one-to-one correspondence manner through the template engine and the mark to generate the target code, specifically:
Replacing the dynamic data with the marks according to the marks, filling the marks into the template file in a one-to-one correspondence manner, and taking 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 at least comprises a path, an encoding mode and a log level of the template file.
The template file is generated according to the repeatability codes of the items, and specifically comprises the following steps:
Determining the operation relation between the repetitive codes according to project operation logic, and setting a control structure;
Calling the repeatability codes through the control structure to form the template file;
the control structure comprises circulation and condition judgment logic.
The present invention additionally provides a computer-readable storage medium storing computer instructions for causing a computer to perform the template engine-based object code generation method.
The present invention again provides an electronic device comprising:
a memory for storing computer instructions;
And the processor is used for realizing the target code generation method based on the template engine when executing the computer instructions.
By adopting the technical scheme, the invention has the following beneficial effects:
1. In the invention, a template file corresponding to an item is preset, and the template file is generated according to the repeatability code of the item. The developer can generate the target code required for a plurality of times by only defining the template file once. Therefore, the workload of repeatedly writing the repetitive codes is obviously reduced, and the development efficiency is greatly improved. In this way, the developer can focus on architecture design and core function implementation at an early stage of the project, and give some repetitive code generation tasks to the templating tool to complete. This not only improves the development efficiency, but also makes the whole development process more efficient and orderly.
2. In the invention, different developers may have different programming habits, so that the styles of codes are inconsistent, and the difficulty of code maintenance and team cooperation is increased. The target code generating method based on the template engine can unify the style of codes and improve the consistency of codes. And generating a template file according to the repeatability codes, so that the generated target codes have uniform formats and styles. This means that even object code generated by different developers will maintain consistent appearance and inherent logic, simplifying subsequent code review and maintenance work. In addition, the template generation target codes can eliminate code style differences caused by personal habits, so that the codes are more standardized and normalized.
In large projects, maintaining consistency of the style of code is particularly important, as it directly affects the readability and maintainability of the code. By using a template engine based object code generation method, a team can more easily maintain and expand code libraries while also facilitating rapid familiarity with project structures for new members.
3. In the present invention, when manually writing code, a developer may introduce errors due to negligence, fatigue or other reasons. By the target code generation method based on the template engine, the opportunity of human intervention is reduced, and the error rate in the code is reduced. The definition of the template file and the data model ensures the quality of the generated code and avoids the problem of non-standardization possibly occurring during manual writing. Once errors are found, all relevant codes can be repaired by only modifying the template file or the data model, and the debugging and correcting efficiency is improved.
In addition, the generated codes are high in quality, clear in structure and easy to maintain and expand. When the code needs to be modified or expanded, a developer can quickly adjust according to the template file and the data model without writing the code from scratch. This approach also helps the team to find problems faster during the code review phase, because the generated code follows predetermined templates and rules, making it easier to identify unexpected situations. This consistency also helps to reduce later maintenance costs, as modifications to the code can be more centralized and systematic.
4. In the invention, the development environment of rapid iteration is adopted, so that the service requirement is changed frequently. By the method for generating codes by the template engine, the template file and the data model can be quickly adjusted when the requirements are changed, and codes meeting new requirements can be regenerated. The method not only greatly improves the response speed of a development team, but also obviously reduces the development cost and time delay caused by the change of the requirements.
Furthermore, the design of the template file and data model supports reuse of code fragments. By defining the general template file and the data model, a developer can reuse the verified code fragments and design modes, and can quickly generate new codes without writing from scratch when the project functions need to be expanded, thereby further improving the development efficiency and the maintainability of the codes. The technical means effectively improves the flexibility of development teams and the overall quality of projects.
5. In the invention, the method for generating codes by the template engine reduces the dependence on individual technical experts and improves the overall capability and efficiency of the team. Team members can work cooperatively by maintaining template files and data models together, reducing the dependency of the project on individual members. In addition, the templated generated codes simplify the process of code examination and integration, and improve team cooperation efficiency. All team members can understand and use the unified template file and the data model, so that team cooperation is smoother, and errors caused by unsmooth communication are reduced. This not only increases the development speed of the project, but also enhances team's cohesive force and overall combat force.
In this way, the team can better distribute tasks, and each member can concentrate on his own expertise without having to worry about code consistency and maintainability issues. In addition, when a member of the team leaves the job or temporarily leaves, others can also take over their work quickly because the code generation process is transparent and reproducible, reducing the time and cost of knowledge transfer. The method also promotes knowledge sharing and technical inheritance inside the team, and helps to cultivate more technical backbones, so that the overall capability of the team and the sustainable development of projects are further improved.
Detailed Description
In order to more clearly illustrate the general inventive concept, a detailed description is given below by way of example with reference to the accompanying drawings.
In the following description, numerous specific details are set forth in order to provide a thorough understanding of the present invention, but the present invention may be practiced in other ways than those described herein, and therefore the scope of the present invention is not limited to the specific embodiments disclosed below.
As shown in fig. 1, a method for generating an object code based on a template engine, the method comprising:
s100, presetting a template file corresponding to the project.
The template file in this step refers to a file for defining the structure and content of the code in the process of generating the code. These files typically contain static text and dynamic tags, where the static text portion is a fixed piece of code and the dynamic tags are used to instruct the template engine to insert specific dynamic data when generating the code.
The method is prepared in advance for the target code generating method based on the template engine, and necessary files for engine calling and dynamic data insertion are provided. By pre-configuring the template files, the template engine can be ensured to accurately load and analyze the files in the code generation process, so that codes meeting project requirements can be efficiently generated.
Specifically, before the project starts, corresponding template files are created and configured according to the requirements and characteristics of the project. These template files define the structure and static portions of the code, as well as the insertion points for the dynamic data. These template files will be loaded and parsed by the template engine for generating the final code. The dynamic markup contained in the template file will instruct the template engine to insert specific dynamic data when generating code.
This step is the initial stage of the overall code generation flow, with the aim of preparing for subsequent code generation.
The object code generating method based on the template engine further comprises the following steps:
s101, loading the template file through a template engine, wherein the template file is generated according to the repeatability codes of the items.
It should be noted that the template engine is a tool or library for combining the static template file and the dynamic data model to generate the final output file. These output files may be HTML pages, configuration files, source code, etc. The main function of the template engine is to insert dynamic data into the template file to generate output content conforming to a specific format and structure.
Specifically, the template engine first parses the template file, identifying static text and dynamic tags therein. The static text portion remains unchanged and dynamic tags are used to indicate where the engine inserts dynamic data.
The template engine binds the data in the data model with the dynamic tags in the template file. The data model is typically a structure (e.g., dictionary, object, etc.) containing key-value pairs, and the engine will obtain corresponding values from the data model based on the variable names in the labels.
After binding is completed, the template engine will generate the final output file. The generated file may be saved to disk, output to a console, or returned directly to an application for use.
Common template engines include Velocity, freeMarker, thymeleaf, jinja, handlebars, etc., where:
The vector is a Java-based template engine that is widely used to generate text content such as HTML, XML, SQL. The Vector Template Language (VTL) is simple and easy to use, and supports grammars such as variables, condition judgment, circulation and the like.
FREEMARKER is another Java-based template engine commonly used for Web application development. FREEMARKER provide a rich template instruction and flexible data binding mechanism.
THYMELEAF is a modern server-side Java template engine, mainly for Web application development. THYMELEAF supports HTML5 syntax, which allows the template file to be previewed directly in the browser.
Jinja2 is a Python-based template engine, widely used in Web frameworks such as Flask and Django. Jinja2 provides powerful template inheritance and macro functions.
Handlebars is a template engine based on JavaScript, supporting the use of clients and servers. Handlebars grammar is simple and easy to learn and use.
The template file is generated according to the repetitive codes of the items. During software development, a large amount of repetitive code is often encountered. These codes are typically structurally similar, content-similar code segments, such as database access layer (DAO) codes, service layer (Service) framework codes, etc. Manually writing these repetitive codes is not only time consuming but also prone to error.
In the application, the template file is generated according to the repetitive codes of the items, which is the key for realizing the multiplexing of the repetitive codes. By multiplexing the repeated codes, the workload of repeatedly writing similar codes can be obviously reduced, and the development efficiency is improved. Thus, not only is the repeated labor reduced, but also the consistency of the generated codes is ensured, and the quality and maintainability of the codes are improved.
In the step, the template file is loaded through a template engine, template analysis is carried out, and static texts and dynamic marks in the template file are identified. The static text portion remains unchanged and dynamic tags are used to indicate where the engine inserts dynamic data. Thereby laying a foundation for merging the data model with the template file to generate the object code.
S102, merging the data model corresponding to the project with the template file to generate target codes;
the template file contains a marker for instructing the template engine to insert dynamic data in the repetitive code, and the data model contains the dynamic data required by the template file.
It should be noted that the data model is a structured representation for storing and organizing data. In the template engine-based code generation process, the data model contains the dynamic data required in the template file. These data are typically stored in key-value pairs, which may be simple dictionaries, complex objects, lists, etc. The purpose of the data model is to provide specific values to the template engine for insertion into the corresponding locations of the template file when the code is generated.
The data model includes key-value pairs, the most fundamental unit in the data model being key-value pairs, where keys are identifiers and values are specific data to be inserted into the templates, although the data model may contain more complex structures such as lists, objects, nested structures, etc. The data in the data model may come from a variety of sources, such as databases, configuration files, user inputs, and the like.
The data model provides specific values for the tags in the template file, ensuring that the generated code meets project requirements. Moreover, the flexibility of the data model allows different codes to be generated according to different requirements. By adjusting the values in the data model, different code variants can be generated.
The template file includes a marker for instructing the template engine to insert dynamic data in the repetitive code. The template engine is instructed by a specific tag to insert the actual dynamic data when generating the code. These tags are typically defined using a specific syntax of the template engine, such as the Vector Template Language (VTL), FREEMARKER, THYMELEAF, etc. The design of the mark improves the accuracy of the dynamic data insertion in the repetitive codes and clarifies the mapping relation between the data model and the template file.
In this step, the data model corresponding to the item is merged with the template file to generate the object code. The template engine matches and merges the dynamic data in the data model with the tags in the template file. The markers in the template file will be replaced by actual values in the data model. The combined result is the final object code, which can be saved in a file, output to a console, or directly returned to an application program for use.
The method comprises the steps of setting a template file and a data model separately, wherein the template file is generated according to the repetitive codes of the items, the data model contains the dynamic data required by the template file, namely, special data in the target code and the repetitive codes are generated separately, and the target code can be generated by combining the template file and the data model through the mapping relation by setting the mapping relation between the dynamic data and the repetitive codes.
Therefore, a large number of similar codes can be generated rapidly through the combination of the template file and the data model, repeated labor of developers is reduced, and development efficiency is improved. The generated codes have consistency, so that possible subtle differences during manual code writing are avoided, the problems of misspelling, grammar errors and the like caused by manual code writing are reduced, the generated codes are ensured to accord with project specifications and standards, and the quality of the codes is improved.
When the project demand changes, a new code can be quickly generated by only adjusting the data model, and quick iteration and development of the project are supported. The separation of the template file and the data model makes the code generation process more modularized, and is convenient for maintenance and expansion. When the code structure needs to be modified, only the template file needs to be adjusted, and a large number of codes do not need to be modified, so that the code generation process is more flexible, and the variable project environment can be dealt with.
The template file and the data model are used for standardizing the code generation process, so that team members can more easily understand and use the generated codes, and the team cooperation efficiency is improved. The template file and the data model can be used as shared resources, team members can be maintained and improved together, and knowledge sharing and accumulation are promoted.
As a preferred embodiment of the present invention, a template file corresponding to an item is preset, specifically:
Identifying the repeatability code from the item, and identifying the dynamic data required by the template file according to variables in the repeatability code;
Determining the type and the target position of the target code to be generated;
defining the mark in the repetitive code, and calling the repetitive code to generate the template file.
The step aims at acquiring a template file and dynamic data required by the template file according to the repeatability code, and defining target code generation requirements, such as the type and the target position of the target code to be generated, so that the generated template file meets the requirements of users.
The identification of the repetitive codes mainly refers to identifying similar code fragments frequently appearing in projects, such as addition, deletion, check and modification operations of a database, user information verification logic and the like. These code segments tend to have similar structures and logic, but the specific implementation details may vary. The identification mode of the repeated codes mainly comprises the steps of finding out the repeated code patterns in the project through means such as code examination, static analysis tools and the like. These modes are typically implementations of basic functions such as data access, business logic processing, etc.
Variables in the repetitive code refer primarily to portions of dynamic changes extracted from the identified repetitive code, such as table names, field names, class names, etc. These variables will become part of the data model for inserting dynamic data in the template file. By code analysis it is determined which parts are fixed and which parts are dynamically changing. The dynamically changing portions are extracted to form key-value pairs in the data model.
Defining the tags in the template file primarily refers to defining tags, such as variable tags, in the template file for inserting dynamic data. These flags instruct the template engine to insert the actual dynamic data when generating the code. The corresponding labels may be defined based on the extracted variables.
The main purpose of determining the type and target location of the object code is to explicitly generate the type (e.g., DAO class, service class, controller class, etc.) and the location (e.g., specific directory or file) of the object code. This helps to ensure that the generated code is properly integrated into the project. In this step, the type of generated code and the storage location may be determined according to the requirements and architecture of the project.
Calling the repeatability codes to generate the template file mainly refers to generating the template file by calling the identified repeatability codes. The template file will contain static parts and dynamic tags for generating the final object code.
In this step, by explicitly generating the type of code, it can be ensured that the generated code meets the requirements and architecture of the project. By explicitly generating the storage location of the code, it is ensured that the generated code can be correctly placed in the project catalog structure, helping to keep the projects clean and orderly. The explicit code types and storage positions enable the catalog structure of the project to be clearer, are convenient for other developers to understand and maintain, can avoid that generated codes cover existing files, reduce potential errors and conflicts, can also ensure that generated file paths are correct, and avoid compiling or running problems caused by path errors. The generated codes can be correctly integrated into projects, so that debugging time caused by code position errors is reduced, and development efficiency is improved.
As a preferred example of this embodiment, the identification of the repetitive code from the item is specifically:
Acquiring a repeated pattern and repeated content of an existing code of the item through static code analysis, and extracting the repeated content from the existing code to generate the repeated code;
And/or, obtaining a repeated pattern and repeated content of an existing code of the item through code similarity analysis, and extracting the repeated content from the existing code to generate the repeated code;
and/or, obtaining a repeated pattern and repeated content of an existing code of the item through code coverage analysis, and extracting the repeated content from the existing code to generate the repeated code;
And/or analyzing and acquiring a repeated pattern and repeated content of an existing code of the project through a code reconstruction mode, and extracting the repeated content from the existing code to generate the repeated code;
and/or analyzing and acquiring a repeated pattern and repeated content of an existing code of the project through a code pattern recognition mode, and extracting the repeated content from the existing code to generate the repeated code;
The type of the repeated pattern at least comprises getter and setter methods, a construction method, exception handling logic, loop and condition judgment, an initialization method and a tool method.
Embodiment 1 obtaining a repeating pattern of an existing code of the item and repeating content by static code analysis, extracting the repeating content from the existing code to generate the repeating code.
Static code analysis is the discovery of repetitive patterns and repetitive content in 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 the developer identify repetitive patterns and repetitive content in the code.
Specifically, the codes in the project are scanned through a static code analysis tool, and frequently occurring similar code segments are identified. These segments generally have similar structures and logic, but the specific implementation details may vary.
Further, specific code segments are extracted from the identified repetitive patterns. These code fragments will form the basis for generating the repetition code.
The extracted repetitive content is abstracted into a common repetitive code. These repetitive codes may be functions, classes, methods, etc. for handling common logic and operations.
Embodiment 2 obtaining a repeating pattern of an existing code of the item and a repeating content by code similarity analysis, extracting the repeating content from the existing code to generate the repeating code.
Code similarity analysis is a technique that identifies similar or duplicate code segments by comparing the structure, syntax, and logic of the code. Such analysis may help the developer find redundant portions in the code for optimization. Common code similarity analysis tools include Simian, cloneDR, CPatMiner, and the like. These tools can identify repetitive patterns by algorithmically calculating the similarity between code segments.
Specifically, codes in the project are scanned through a code similarity analysis tool, and frequently occurring similar code segments are identified. These segments generally have similar structures and logic, but the specific implementation details may vary.
From the identified repeating pattern, a specific code segment is extracted. These code fragments will form the basis for generating the repetition code.
The extracted duplicate content is abstracted into a common code template. These templates may be functions, classes, methods, etc. for handling common logic and operations.
Embodiment 3 obtaining a repeating pattern and repeating content of an existing code of the item by code coverage analysis, extracting the repeating content from the existing code to generate the repeating code.
Code coverage analysis is a technique to evaluate the degree of coverage of a test case with code. By running test cases, which code lines are executed and which are not, are recorded, thereby evaluating the sufficiency of the test. Common code coverage analysis tools include JaCoCo, cobertura, clover, etc. These tools may generate detailed reports showing which code lines are covered by the test and which are not.
Specifically, the codes in the project are scanned through a code coverage analysis tool, and frequently occurring similar code segments are identified. These segments generally have similar structures and logic, but the specific implementation details may vary.
From the identified repeating pattern, a specific code segment is extracted. These code fragments will form the basis for generating the repetition code.
The extracted duplicate content is abstracted into a common code template. These templates may be functions, classes, methods, etc. for handling common logic and operations.
Embodiment 4 analyzing and acquiring the repeated pattern and repeated content of the existing code of the project through a code reconstruction mode, and extracting the repeated content from the existing code to generate the repeated code.
The code reconstruction refers to structural adjustment and optimization of the code on the premise of not changing the external behavior of the code, so as to improve the readability, maintainability and expansibility of the code. Through code reconstruction, repeated patterns in the codes can be identified and eliminated, common logic is extracted, and the codes are generated more simply and efficiently.
Specifically, through the code reconstruction process, frequently occurring similar code segments are identified manually or using tools. These segments generally have similar structures and logic, but the specific implementation details may vary.
From the identified repeating pattern, a specific code segment is extracted. These code fragments will form the basis for generating the repetition code.
The extracted duplicate content is abstracted into a common code template. These templates may be functions, classes, methods, etc. for handling common logic and operations.
Embodiment 5 analyzing and acquiring a repeated pattern and repeated content of an existing code of the item by means of code pattern recognition, and extracting the repeated content from the existing code to generate the repeated code.
Code pattern recognition is a technique that automatically recognizes common patterns and duplicates in code by analyzing the structure, syntax, and logic of the code. Such techniques may help developers find redundant portions in code for optimization. Common code pattern recognition tools include RIPS, fortify, sonarQube, etc. These tools may automatically identify the repeating pattern in the code by an algorithm.
Specifically, the codes in the project are scanned through a code pattern recognition tool, and frequently occurring similar code fragments are automatically recognized. These segments generally have similar structures and logic, but the specific implementation details may vary.
From the identified repeating pattern, a specific code segment is extracted. These code fragments will form the basis for generating the repetition code.
The extracted duplicate content is abstracted into a common code template. These templates may be functions, classes, methods, etc. for handling common logic and operations.
In the step, the repeatability codes are confirmed according to the code block length, the variable method name and the logic complexity, and the types of the repetition modes at least comprise getter and setter methods, a construction method, exception handling logic, loop and condition judgment, an initialization method and a tool method.
Specifically, in the check repetition code, whether or not to repeat the content is determined based on the length of the code block. Longer code blocks, if present in multiple places, are likely to have duplicates. For example, code blocks exceeding 10 lines, if present in multiple places, are likely to have duplicates.
And judging whether the code is repeated or not through the similarity of the variable and the method name. The same variables and method names generally mean similar logic. For example, the same variables and method names generally mean similar logic.
Whether the code is repeated is judged by the logic complexity. Complex logic, if present in multiple places, may need to be abstracted into a common method or class. For example, complex try-catch statements may need to be abstracted into a common method or class if they occur in multiple places.
Of the types of repeating patterns, getter and the button methods are access methods of attributes, which are generally used for encapsulating the internal states of the class;
the construction method is a method for initializing an object;
exception handling logic refers to a block of code that handles exceptions, typically containing try-catch statements;
loop and condition predicate refers to a code block used to traverse the data structure and conditional branches;
an initialization method refers to a method for initializing an object or resource;
The tool method refers to a general auxiliary method such as character string processing, date conversion and the like.
In the step, the generated repeatability codes have consistency through abstracting the public logic, so that possible subtle differences during manual code writing are avoided, the problems of misspelling, grammar errors and the like caused by manual code writing can be reduced, and the quality of the codes is improved.
By arranging and multiplexing the repeated codes, the workload of manually writing similar codes by developers is reduced, and the development efficiency is improved. When the project demand changes, a new code can be quickly generated by only adjusting the data model, and quick iteration and development of the project are supported.
Specifically, the repeated content is extracted from the existing code to generate the repeated code, specifically:
counting the number of times of occurrence of the code segments in the existing code by using a code analysis tool;
Taking the code segments with the times larger than a specified threshold value as the repeated content, and carrying out code formatting through a code formatting tool to form a repeated code;
And adding a custom annotation to the repeatability code, wherein the custom annotation is used for enabling calling of the repeatability code.
The code analysis tool includes SonarQube, PMD, findBugs and the like. These tools can scan the code to identify frequently occurring code segments. Before analysis, a rule set of a tool needs to be configured, and repeated detection of codes is focused on.
Code formatting tools include IntelliJ IDEA, eclipse, prettier, and the like. These tools can automatically format the code, ensuring that the code styles are consistent.
Specifically, the number of occurrences of the code segment is counted using a code analysis tool:
the method comprises the steps of selecting a tool, such as SonarQube, configuring a rule set of the SonarQube, focusing on repeated detection of codes, running analysis, running the SonarQube, scanning the codes in the project and generating a report.
Counting the occurrence times of the code fragments:
Code segments are extracted, and frequently-occurring code segments are extracted from a report generated by SonarQube;
the number of times each code segment appears in the project is counted.
Determining duplicate content:
The threshold is set and a threshold is set, for example 5 times. Code segments that occur more than 5 times are considered duplicate content.
And manually checking the identified repeated content to confirm that the repeated content is indeed repeated.
Code formatting by a code formatting tool:
Selection tools, such as selection IntelliJ IDEA;
Formatting codes, namely formatting the extracted repeated content through a IntelliJ IDEA code formatting function to form a unified code style.
Generating a repeatability code:
and abstracting the common logic to abstract the formatted repeated content into a common code template. For example, the add-delete-modify operations of the database are abstracted into a generic approach.
Adding custom annotations to the repeatability code:
Defining a custom annotation, and defining a custom annotation for marking the repetitive code so that the repetitive code can be called;
Application annotation-custom annotations are added to the generated repetitive codes to invoke these codes where needed.
As another example under this embodiment, the mark is defined in the repetitive code, specifically:
Identifying a fill location of the dynamic data in the repetitive code to generate a placeholder, the placeholder for storing the dynamic data;
And determining the data model transmitted to the template file according to the required dynamic data in the template file, wherein each dynamic data in the data model is matched with each placeholder in a one-to-one correspondence manner.
In this step, the placeholder is typically a special tag that instructs the template engine to insert the actual dynamic data when generating the code. Common placeholder formats include $ { variabalename }, # variabalename, etc.
Specifically, the fill location of the dynamic data is identified:
Placeholders are defined, and in the template file, placeholders for storing dynamic data are defined. For example, $ { tableName } is used to represent table names, and $ { FIELDNAME } is used to represent field names.
The placeholder format is selected, and commonly used placeholder formats include $ { variableName }, # variableName, etc.
Determining a data model:
Analyzing the template file, analyzing placeholders in the template file, determining required dynamic data, such as CLASSNAME, TABLENAME, FIELDS, VALUES, SETFIELDS, ID and the like;
And creating a data model, wherein the data model comprises key value pairs of dynamic data and is used for inserting specific values into the template file according to the required dynamic data.
The mapping relation between the template file and the data model is provided through the design of the placeholder, and the filling mode of filling dynamic data in the data model into the template file is indicated when the data model corresponding to the project is combined with the template file.
Dynamic data can be flexibly inserted into the template file through the placeholders. This means that the template file can accommodate a variety of different scenarios and requirements without having to write templates separately for each case. When the project demand changes, new codes can be generated by only adjusting the data in the data model without modifying the template file. This greatly improves the flexibility and adaptability of code generation. The mapping relation and the determination of the filling logic are standardized in the code generation process, so that team members can more easily understand and use the generated codes, and the team cooperation efficiency is improved.
The template file defines the basic structure and logic of the code, ensures that the generated code conforms to a unified standard, and is convenient for team members to understand and maintain. The template file defines the basic structure of the code, so that the generated code has clear logic and structure, and is convenient to read and understand.
As a preferred embodiment of the present invention, the data model corresponding to the item is combined with the template file to generate the object code, specifically:
Configuring the template engine;
and filling dynamic data in the data model into the template file in a one-to-one correspondence manner through the template engine and the mark so as to generate the target code.
This step aims at filling dynamic data in a data model into the template file in a one-to-one correspondence by a template engine to generate the object code.
Specifically, the template engine is configured to:
Selecting a template engine, selecting a proper template engine, such as Velocity, freeMarker, thymeleaf;
Installation and configuration, installation and configuration is performed according to the documents of the selected template engine, for example, using Maven to add dependencies.
Loading a template file:
And the template engine loads the template file according to the configured path, analyzes placeholders in the template file and determines the required dynamic data. Placeholders in the template file are analyzed to determine the dynamic data required. For example CLASSNAME, TABLENAME, FIELDS, VALUES, SETFIELDS, ID, etc.
Creating a context:
A context object is created, the data model is passed to a template engine, and a context object is created. The context object is used to store dynamic data for use by the template engine in generating code.
Generating target codes:
Combining the data model with the template file, wherein the template engine matches and combines the data in the data model with the placeholders in the template file;
And generating an object code, namely obtaining a final object code as a combined result, and storing the final object code in a file, outputting the final object code to a console or directly returning the final object code to an application program for use.
As a preferred example in this embodiment, the template engine and the tag are used to fill the dynamic data in the data model into the template file in a one-to-one correspondence manner to generate the object code, specifically:
Replacing the dynamic data with the marks according to the marks, filling the marks into the template file in a one-to-one correspondence manner, and taking 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 at least comprises a path, an encoding mode and a log level of the template file.
In this step, the attribute information of the template file includes:
A path for specifying a path of the template file;
the coding mode is used for designating the coding mode of the template file, such as UTF-8;
log level for setting log level of the template engine, such as DEBUG, INFO, etc.
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 a final target code, and stores the generated target code into the file and outputs the target code to the console or directly returns the target code to the application program for use.
In the step, the flexibility and maintainability of configuration can be remarkably improved by setting the path, the coding mode and the log level of the template file in the template engine. And the attribute information is managed in a centralized way, so that the management and maintenance are convenient, and if the attribute is required to be changed, only one configuration is required to be modified. The method enables different projects or environments to be capable of easily adjusting configuration, avoids hard coding paths, reduces path errors and improves code robustness. And setting a coding mode (such as UTF-8) to ensure that file reading and writing have no messy codes and unify coding standards. Setting log levels (e.g., DEBUG, INFO) facilitates debugging and monitoring while optimizing performance. Centralized configuration makes the code clearer and more readable, and adding notes and documents further improves intelligibility. Standardized configuration reduces problems in team collaboration, and configuration files promote knowledge accumulation as shared resources. And the environment variables are used for easy deployment, and the automation degree and the deployment efficiency are improved by integrating the environment variables into the CI/CD flow.
As a preferred embodiment of the present invention, the template file is generated according to the repetitive code of the item, specifically:
Determining the operation relation between the repetitive codes according to project operation logic, and setting a control structure;
Calling the repeatability codes through the control structure to form the template file;
the control structure comprises circulation and condition judgment logic.
During the development of projects, repetitive code logic is often encountered, which may be managed and generated by control structures (e.g., loops and conditional decisions).
Loop structure-if multiple similar code blocks need to be generated, a loop structure may be used. For example, when generating a plurality of DAO classes, the information for each class may be traversed using a loop to generate the corresponding code.
Condition judgment logic if the generation conditions of some code blocks are different, condition judgment logic may be used. For example, depending on the nature of the database table (e.g., whether there is an auto-added primary key), it is determined whether to generate certain specific codes.
Calling the repeatability code in the template file, using the control structure to call the repeatability code. And generating a final template file according to different conditions and cycle times by controlling the structure.
The step realizes the calling and connection of the repeatability codes through the control structure, and forms the template file.
The present invention also provides a computer-readable storage medium for storing computer instructions for causing a computer to execute an object code generation method based on a template engine. Therefore, any technical effect of the target code generating method based on the template engine can be achieved, and the description is omitted here.
The present invention again provides an electronic device comprising:
a memory for storing computer instructions;
And the processor is used for realizing the target code generation method based on the template engine when executing the computer instructions. Therefore, any technical effect of the target code generating method based on the template engine can be achieved, and the description is omitted here.
The invention can be realized by adopting or referring to the prior art at the places which are not described in the invention.
In this specification, each embodiment is described in a progressive manner, and identical and similar parts of each embodiment are all referred to each other, and each embodiment mainly describes differences from other embodiments.
The foregoing is merely exemplary of the present invention and is not intended to limit the present invention. Various modifications and variations of the present invention will be apparent to those skilled in the art. Any modification, equivalent replacement, improvement, etc. which come within the spirit and principles of the invention are to be included in the scope of the claims of the present invention.