The concept of agile development has been popular for a long time. In the development iteration stage of agile development, we can use five steps to effectively improve the code quality of the entire project.
In the Java project development process, due to developers' experience, Java coding habits, and lack of unified standards and management processes, the code quality of the entire project is often poor and difficult to maintain, large test investment and cycle are required. These problems will be particularly prominent in a new project with incomplete predictability and completeness in its initial construction, requirements and design.
1 shows that the agile development process goes through demand research, case analysis, and Case decomposition to enter the development iteration stage. In each iteration process, the following steps can be taken to ensure and improve the Code Generation quality of the entire project: uniform coding specifications and code styles; static code analysis (staticcodereview); unit test; continuous integration; Review and Refactor ). The following describes each step and the tools and methods used.
Figure 1. Java code quality assurance steps in Agile Development
Step 1: Unified coding specifications and code styles
Standardized and unified coding increases the readability and maintainability of the project code, but the actual situation is that the coding styles of Java code developers in the project team are often different, this may be caused by different experience habits or lack of coding standards. In this way, other project members or maintenance personnel need to spend more time reading the project code to understand the intent of the Code author, therefore, it is very important to develop and adopt unified coding specifications. The code specification mainly includes the following aspects:
◆ General rules and format specifications. For example, code indentation, block specification, and maximum code length per line.
◆ Naming rules. Such as package name, class name, variable, method, interface, parameter, and other naming rules
◆ Document specifications. For example, the class file header declaration, class annotation, member variable, and method annotation specifications.
◆ Programming specifications. Such as exception, concurrency, and multithreading.
◆ Other specifications. For example, log format, attribute file format, return value, and Message format.
The coding standards of the project can be determined by referring to some existing Java programming standards books and other relevant materials combined with the project itself. The books available for reference include the Java programming style (English document name: theElementsofJavaStyle ). Coding standards should be documented and concise, and project members should be organized to learn together to ensure that all Members understand all entries correctly.
Once the encoding specification is determined, you can use the functions provided by Eclipse to control the code style and format. The specific method is to click the Preference menu item in Eclipse Windows, and find the Sub-item CodeStyle (2) under the Java node in the left column of the Preferences dialog box that opens ), this item and its subitem allow you to control the style of Java code.
Figure 2. Eclipse code style setting window
For example, to use an automatic formatting tool, you can create a custom format based on the default code format configuration provided by Eclipse. On the Formatter panel, click New, enter a New name, and select a default configuration as the initialization format, as shown in 3.
Figure 3. Create a new code format Configuration
Click OK to modify the custom format in the new window. 4.
Figure 4. Create a new code format Configuration
Click Apply to save the modification. You can also click Export to Export the current format definition to an XML file, in this way, other members of the project team can easily Import the XML file by clicking the Import button in Figure 3 to use the same code format definition.
In this way, you can Format the Code through the Source-> Format menu on the Eclipse interface before submitting code to the version control server, so that the code of the entire project has the same Format. You can also set other projects in CodeStyle to control the style of Java code. After exporting all these style files into XML files, archive them together with the encoding specifications for use by all project members.
Step 2: static code analysis
After the source code development, the following work is to review and test the code. In addition to running the test code to check the function, some static analysis tools can be used to quickly and directly improve the code quality. Static code analysis tools do not need to run code. They can analyze Java files and Class files directly, and quickly find errors and potential defects in the Code by setting some check conditions. There are many static analysis tools, such as FindBugs, PMD, and IBMRationalTool. Select FindBugs as the static code analysis tool. FindBugs can be integrated with the daily development tool Eclipse. during the development process, you can easily start static code check. Check the Class file or JAR file and compare the bytecode with a set of defect modes to find possible code problems. In the Eclipse development environment, after installing Findbugs using plug-ins, The FindBugs configuration options will be displayed in the Eclipse configuration options. You can configure your project and select the desired Detector to check the code.
Figure 5. FindBugs configuration options
After setting your own rules, right-click the code folder to be checked to start the FindBugs check. The code can be a project or just a few files.
Figure 6. Run FindBugs
After the check is completed, the FindBugs view will appear, displaying all the check results according to the error group. Click an error in the result and the corresponding code is automatically opened. When all errors or potential errors are corrected according to the rules, the Code passes the static code check. The FindBugs check result can be an XML file or a text file, which facilitates Project Integration Management and check and storage.
Figure 7. FindBugs check results
Step 3: unit test
Unit test case design and review
Unit testing is an important quality guarantee link in the software development process. In this phase, design and review are very important to ensure the integrity and effectiveness of the entire unit testing process. In the design phase, it is necessary to take into account which code units should be tested, the relationships between tested units, test strategies, and unit test case design, finally, the unit test case design document is output to guide specific unit test execution. In the case design, the function correctness of the unit is ensured by defining the code unit input and the expected output. The Boundary Value test and exception test are very important. At the same time, the test case and function block matching methods are used to measure the integrity of the test case design.
After the case design is complete, the next step is to review the test case. My personal understanding and experience are always limited. We can use the collective power of case reviews to check for missing cases and further ensure the effectiveness of the test cases. Unit testing is a white-box test. It mainly designs test cases by analyzing the logic structure of the Code. Therefore, it is best for reviewers to consider understanding the logic structure of the Code as a prerequisite, if the reviewers are from the relevant modules, they can also effectively discover problems caused by module relevance and dependency.
Simulation object technology
In actual projects, developers often need to interact with other code modules or systems, these real objects to be called are often difficult to instantiate, or they cannot be used for testing in some cases. For example, the behavior of real objects cannot be predicted, the behavior of real objects is difficult to trigger, or the running speed of real objects is slow. At this time, we need to use the simulated object technology (Mock) to simulate the real objects that our code depends on to help complete the test and improve the test coverage rate, this improves the code quality. Simulation object technology uses the interface-oriented programming. Because the Code calls the interface directly, the Code does not know whether the referenced object is a real object or a simulation object, in this way, code testing can be completed smoothly. There are many simulation technologies, such as jMock, EasyMock, Mockito, and PowerMock. Among them, Mockito eliminates the need for the expected behavior and avoids a lot of initialization of these codes.
Figure 8. Mockito example
In the process of simulating an object, first simulate a List object listing List to be called, and then set the behavior of this object. When get (0) is called, return "first ". In this way, the test code can use this object to test our function code. When we need to call and return values, we can smoothly obtain the returned values of the simulation object. It is also necessary to simulate the error situation of the simulated object to ensure that the code correctly processes the error.
Test Coverage Rate Analysis
To measure the quality and coverage of unit tests, the code of unit tests must be tested for coverage analysis. Common metrics for measuring test coverage include statement coverage, branch coverage, path coverage, condition coverage, and method coverage. The specific indicators can be determined based on the actual situation of the project, so as to avoid the impact of excessive indicators on the overall progress of the project by increasing the workload of code developers.
EMMA is a popular open-source Java test coverage analysis tool that supports various types of test coverage analysis such as classes, methods, code lines, and basic code blocks, you can export the coverage analysis result to reports in multiple formats and highlight different coverage states in multiple colors. EclEmma is an EMMA-based Eclipse plug-in for testing coverage analysis in EclipseIDE. 9. After writing the test case, right-click the test class and choose CoverageAs> JUnitTest.
Figure 9. Running Test Coverage Analysis
After the unit test is completed, the Coverage of the selected test is displayed in the Coverage view. Double-click a specific class to view the highlighted overwrite analysis result, as shown in 10. Red indicates that the row is not covered in the test, yellow indicates partial coverage, and Green indicates that the row is overwritten in this test.
Figure 10. view test coverage analysis results
In the Coverage view, you can right-click to export the test Coverage analysis results to the desired format, such as HTML.
Figure 11. Export test coverage analysis results
Figure 12 shows the exported report.
Figure 12. Test Coverage Analysis Report
To ensure the effectiveness and quality of unit tests, a lower limit of test coverage can be defined. For example, the coverage rate of all packages and classes must exceed 80%. However, it is worth noting that we should not simply pursue high coverage rate, but also pay attention to the quality of test cases. If the test cases are written incorrectly, it makes no sense even if the test coverage rate is high.
Step 4: continuous integration
Continuous integration (ContinuousIntegration) is a series of tools, methods, and rules to quickly build and develop code and automatically test the code to improve the efficiency and quality of development code. The Automatic Build tool can be used to build the submitted code at any time and provide a version that can be used for testing. This allows users and developers to view the same function at the same time and detect problems and errors as soon as possible, you can also get feedback from testers and users as soon as possible.
To achieve continuous integration, we must use a series of tools to automate repetitive work in the development process. Build an automatic building server to automatically perform unit tests and release new versions. An integrated server can provide results reports for the building process, automatically notify developers of the building results, and save historical data. IBMRationalTeamConcert (RTC) can provide task management, project plan arrangement, code version management control, automatic build of available versions, and generate build result reports. These processes constitute the continuous integration process of the project. The automatic build of the version and the automatic unit test of the Code are the key processes of continuous integration. RTC provides strong support for these processes.
Automatic Build
RTC provides buildengine for building. The first choice is to start buildengine and establish a connection with the RTC server. Create a build definition for the project. In this definition, you need to set the code of which modules to compile, the ANT file to be broken to start compilation, and the parameters in the compilation process. When these are all ready, compilation is a simple task for projects.
You can see that by clicking build request on build definition, a build process can be triggered. Select the required building parameters, and the process will run in the background. Every developer who makes some code changes and commits can trigger a new build process to ensure the validity of our code. Apply for a new build process 13. Figure 14 shows.
Figure 13. Apply for a new build
Figure 14. Build the application page
After the build is complete. The RTC server provides the build result report. Developers can query the detailed information of this build.
Figure 15. Build results
Throughout the development process, the build version process should be countless times. Through each build, you can get the compilation of the code at that time and get a runable software version. In terms of build definition, RTC supports setting build plans. Automatically trigger a build at a scheduled time.
Figure 16. Build Definition
Automatic unit test
The building can be automated. What about unit tests that focus on improving the code quality? If every day's code and every version of code have passed our unit test, we can ensure the quality of the Code. In the automatic call process of build scripts, ANT scripts of JUnit, EMMA, and FindBugs can be added to call each build, these checks can be automatically tested. All these tests must generate test results reports. RTC can use Hudson, an open-source tool, to integrate the test reports for easy access.
Figure 17. Automatic Test report
Step 5: code review and Reconstruction
Code review is an important step in Java project development. Code review can help you discover problems that cannot be found in the static code analysis process, such as whether the code compilation conforms to the coding specifications, whether the code is logically or functionally incorrect, whether the code needs to be improved in terms of execution efficiency and performance, whether the comments of the Code are complete and correct, and whether the code is redundant and repetitive. Code review can also help new project members quickly learn and understand projects, promote experience sharing, and ensure good communication between project members. The Code review mainly includes two forms: peer review and group review ). Peer review mainly refers to the mutual review among project members. A group review refers to the review meeting where project members review the project code together.
To improve the effectiveness and efficiency of code review, you can use some external tools. Common Code review tools include Jupiter and CodeStriker. Jupiter is an open-source Eclipse plug-in that allows members to locate the review comments to specific lines of real code. Because the code review results are saved as XML files, therefore, you can submit the results to the version management server for sharing. Figure 18 shows the code review page using Jupiter.
Figure 18. Jupiter code review page
After the code review task is created, Jupiter divides the code review into three phases: the personal review phase (IndividualPhase), the Team review phase (TeamPhase), and The ReworkPhase ). During the individual review phase, the reviewer records the code issues or defects found, and each issue is saved as a record in the review form. During the Team review stage, all or part of the team members will make a qualitative analysis of the problems found during the individual review stage. If the problem exists, the problem will be assigned to a member for resolution, in Jupiter, set the problem to the corresponding status. In the problem repair phase, the team members fix their own problems and set the corresponding records to the correct status, such as resolved.
Codestriker is a common Web-based code review tool. The Code review can be performed on a specific line or the entire code file. The review comments will be stored in the database. Reviewers can view comments from other people at the same time, and the code Author can also reply to a specific comment. Codestriker supports email notification and can be integrated with the version control server to track and display changes in file content. Figure 19 shows the interface of Codestriker.
Figure 19. Codestriker report page
In practice, it is time-consuming to review all codes in a group. Therefore, you can select some core codes for group review based on the actual situation, or arrange a large number of group reviews in the early stage of the project, the members of the project group have a good understanding of the Code review standards and requirements. After the code review experience is improved, the number of group reviews can be gradually reduced, in this way, the quality of most codes can be guaranteed even if only peer reviews are conducted.
Problems discovered through code review should be solved through code reconstruction in a timely manner. Minor reconstruction that does not involve multi-person code can be completed by the project members themselves by using the reconstruction function of Eclipse, different code written by different project members to implement the same function should be integrated into public classes or methods through discussion. Complicated or relatively high-level reconstruction work. For example, changes to the Code organization form at the project level must be discussed by the entire project team.
Conclusion
There are no static and omnipotent processes and methods for software development. I hope you can get inspiration and benefits from this article. Based on the characteristics of your actual project, we hope you can practice the above steps and methods, improve and improve the code to create efficient and high-quality Java code, and lay a solid foundation for the success of your project.