Home > News content

Save the Code

via:博客园     time:2017/6/19 15:01:44     readed:777

Text / zhou yugang

Has 10 years of experience in JAVA EE development, as a senior consultant at ThoughtWorks. Prior to joining ThoughtWorks, he worked as an architect in a leading domestic airline business, focusing on ongoing delivery practices and large enterprise application architecture governance.

This article originated from a continuous delivery of the consulting project, was to guide the customer team of Java engineers to do Code Review, found a very interesting phenomenon: an engineer on the Code Style particularly concerned, so most of the time in the Code Review The engineer is pointing out where the format is wrong, but the team did not find the improvement method, each conclusion is "next time I pay attention to that." "I appreciate the engineer's serious attitude towards Code Style, so he initiated the idea of ​​saving Code Style."

Points

  • Code Style is not a personal preference problem, it will affect the efficiency of the team should be regarded as engineering practice to be taken seriously.
  • Code Style requires end-to-end tool support to solve problems early and avoid technical debts.
  • Using Checkstyle as the core tool to support the Java project Code Style implementation program.

Code Style is an engineering practice

I am the right side of the style of loyal fans, if let me work in the project to see the left style of the code, you guess what my reaction is.

Well, maybe I do have some obsessive-compulsive disorder on the code style, but in fact, Code Style is not just that the code is so easy to read, if not in accordance with the practice to write code, and even make the reader doubts.

Private Listener listener = new Listener ()

// So Listener looks like a class? {};

// Oops, it is an interface

If the code readability is not enough to impress you, then imagine this scene, your colleagues said he fixes two empty pointers, please help Code Review, you look at the revised history of this document, at first glance Many changes seem to be a big move. However, in fact, most of the changes are code format adjustment, only two changes and the need to review issues related.

(It seems that the colleague's IDE uses a different auto-indentation setting that causes all rows to be indented)

The reason for this is that the team did not pay attention to Code Style, did not take it as an engineering practice, neither had agreed to it nor did it use the tools to help it.

It is in accordance with the standards of engineering practice to implement Code Style

This article will focus on the Java project Code Style tool support, but before that, your team needs to make some decisions together:

  1. What kind of Code Style?

    Everyone may have a preference style, but in front of teamwork, a certain compromise is needed. Some companies or organizations have a unified Code Style guidance standard, and it is a good choice (but to make sure that such a unified guidance standard is in the direction of the developer's advice, and your team can Cut yourself, but at least ensure that the same style is used at the Repository level.

  2. How do I handle a submission that does not conform to Code Style?

    We often lazy in the way after the remedy, my suggestion is not to let the code does not meet the agreed code into the code base. For legacy projects, especially large projects, you can choose part of the code as a scope of implementation, focus on repair after the strict implementation of the problem, should not be too hasty, the last team tired had to give up.

We all know that the way of manual supervision and inspection is unsustainable and unreliable to see which tools can help.

Laziness is the first productive force

Engineering practice can not be without automatic tool support, in the Java ecosystem, Code Style tool should be the most famous Checkstyle, it can be through the XML formExternal DSLTo define the Style of the Code Style, for example, you can find it from hereGoogle's Java Checkstyle configuration fileThe Here I will not elaborate on Checkstyle itself, on the contrary, I will explore more about how to use Checkstyle engineering, in the delivery of the code of the various activities, we can use Checkstyle, 360 il / no dead check.

(And Code Style-related code delivery lifecycle)

Hold the quality of the submission

In order to implement the decision not to comply with the agreed code into the code base, you can set the Code Style checkpoint on the server side.

(Priority to hold the code to submit the server to check, you can consider using the CI server to achieve)

From the implementation level, there are two ways:

First, in the SCM (Source Control Management, such as Git / SVN) server settings check items, if not compliance refused to submit, but this approach is relatively easy to achieve, and the general SCM server is not managed by the development team, set up not Flexible and inconvenient.

Second is the use ofContinuous IntegrationServer, the development team will trigger a construction once, we can add a Checkstyle in the script to check, if there is no compliance code to let the construction failed to tell the submitter to repair the Style problem immediately. I recommend this scenario because the associated tool support is very mature and simple to implement, and the build process can be replicated in the developer's local environment so that Checkstyle checks forward and provides faster feedback in subsequent improvements. If the team uses Maven / Gradle and other build tools, you can use the plug-in way to achieve Checkstyle check and embedded into the entire construction process. So CI server as long as the call to build the script on the line.

Verify the Style locally at the developer

(In the developer to achieve local verification, feedback gateway move forward)

In the realization of the CI verification, you can proceed to achieve the local developers to verify, so developers do not have to wait until the submission of code to the server will get feedback. As a result of the use of the tool before the plug-in program, so developers can run on the local construction can be verified. For example, Gradle provides Checkstyle plug-in support, you can find here Gradle Checkstyle Plugin detailed configuration documents, if you use Maven, you can refer to here. Now only need a command, the developer can verify the local code for a long time.

# Build.gradle
# Omitted plugins
Apply plugin: 'checkstyle'
Checkstyle {
    ConfigFile = file ("config / checkstyle.xml") // specify the checkstyle configuration file
    ToolVersion = "7.4" // Specifies the version of the checkstyle tool, and some style rules have version requirements
}
CheckstyleTest.exclude "** / contractVerifierTest **" // ignore checking the generated code, this pot we do not back

// If the checkstyle warning also causes the build to fail, the plugin default only supports checkstyle error
// Fail build on Checkstyle Warning Violation & middot; Issue # 881
Tasks.withType (Checkstyle) .each {checkstyleTask - & gt;
    CheckstyleTask.doLast {
        Reports.all {report - & gt;
            Def outputFile = report.destination
            If (outputFile.exists () & amp; & amp; outputFile.text.contains ("& lt; error")) {
                Throw new GradleException ("There were checkstyle warnings! For more info check $ outputFile")
            }
        }
    }
}

Now only need a command, each developer will be able to verify the local Code Style. You can be thereHereFind the detailed configuration documentation for the Gradle Checkstyle Plugin. If you are using Maven, you can refer toHereThe

➜ court-booking-backend (master) ✗ ./gradlew check
Starting a Gradle Daemon (later builds will be faster)
: CompileJava
: ProcessResources UP-TO-DATE
: Classes
: CheckstyleMain [ant: checkstyle]
    [WARN] /Users/twer/Workspace/restbucks/court-booking-backend/src/main/java/com/restbucks/courtbooking/http/CourtRestController.java:16:
    'Method def' child have incorrect indentation level 4, expected level should be 8. [Indentation]: checkstyleMain FAILED
FAILURE: Build failed with an exception

Local validation is nice, but I sometimes forget to execute

(Let the machine do the chores)

Sometimes, developers modify the code will forget to perform a local check on the submission code, it is best to submit the code before the implementation of the automatic check. If you use Git, you may think of Git commit hook, such as this is my commonly used pre-commit hook

#! / Bin / sh
# From gist at https://gist.github.com/chadmaughan/5889802

# Stash any unstaged changes
Git stash -q - keep-index

# Run the tests with the gradle wrapper
./gradlew clean build

# Store the last exit code in a variable
RESULT = $?

# Unstash the unstashed changes
Git stash pop-q

# Return the './gradlew build' exit code
Exit $ RESULT

Copy the script to.git / hooks /Under executionGit commitThe time will automatically trigger the check, if the check fails to submit failed. But the problem is.gitAnd can not be submitted to the remote code warehouse, then in addition to manual distribution and copy, there is no better way to share this mechanism in the team?

Can save the curve! Put the pre-commit into version control (see below)Config / pre-commit), And then use the extension of the build tool to automatically complete the copy of the work, so you can indirectly achieve git hooks between the team sharing.

# Build.gradle

Task installGitHooks (type: Copy) {// copy the pre-commit to the specified location
    From new File (rootProject.rootDir, 'config / pre-commit')
    Into {
        New File (rootProject.rootDir, '.git / hooks')
    }
    FileMode 0755
}

Build.dependsOn installGitHooks // set the implementation of the build task will automatically trigger the installGitHooks task

Close the encirclement, edit feedback

(Real-time feedback)

Before the build-based tools are good, but for developers, it is best to move the feedback to the editor, and visualization. Fortunately, Checkstyle's ecosystem is very mature, the mainstream IDE have plug-in support to Intellij Idea, for example, you can useCheckstyle-ideaPlug-in, so that team members manually set the plug-in, use the project's checkstyle configuration file (I have not yet found the way of automated configuration, perhaps gradle idea plug-in can?)

(Checkstyle-idea plug-in configuration and effects)

With automatic real-time inspection, it is best to be able to automatically format the IDE and Checkstyle configuration file linked to, or automatically formatted to give you trouble.

(For the IDE import checkstyle configuration file as the basis for automatic formatting)

If you are not even too lazy to format, you can trySave ActionsPlugin, it can be in Intellij save the file automatically when the code formatting and other actions.

(This plugin currently has some problems with some of the files, you can ignore the file path exclusion)

to sum up

  1. Code Style affects work efficiency, and the team should pay attention to engineering practice.
  2. Code Style can not rely on manual monitoring and inspection, should provide end-to-end tool support
  3. Server-side inspection (recommended integration into CI build steps)
  4. Development environment check (using Checkstyle plugin for each build tool)
  5. Automatic submission check (git pre-commit hook and share)
  6. IDE enhancements (checkstyle plugin real-time visual feedback / automatic automatic formatting!)
  7. The above tools are based on the same Checkstyle configuration file and incorporate version control

Hope that these tricks can save Java Code Style obsessive-compulsive disorder :)

China IT News APP

Download China IT News APP

Please rate this news

The average score will be displayed after you score.

Post comment

Do not see clearly? Click for a new code.

User comments