Four tools to improve the quality of Android code: android code

Source: Internet
Author: User
Tags checkstyle

Four tools to improve the quality of Android code: android code

In this article, I will introduce how to improve the quality of your Android code through different automation tools such as CheckStyle, FindBugs, PMD, and Android Lint. It is very useful to check your code in an automated way, especially when you work in a team, in order to maintain a strict syntax format in your code and avoid many bad habits and errors. I will explain in detail how to directly use these tools to build scripts through Gradle and configure them when you are free.

Fork example

I strongly recommend that you copy this project, even though all the cases I will introduce come from it. At the same time, you will be able to test your understanding of these tools.

About Gradle tasks

The concept of a Gradle task (meaning in Gradle) is the basis for understanding this article (and how to write a Gradle script in a common way. I strongly recommend that you read these two documents about the Gradle task (This and this ). This document contains a large number of examples, so it is very easy to start learning. Now, I assume that you copied my Repo, you imported this project to your Android Studio, and you are familiar with the Gradle task. If not, don't worry. I will do my best to make my explanation more meaningful.

Hierarchy of sample projects

You can split the gradle script file into many files. I already have three gradle files:

  • Files in the root folder. These files are more or less about the configuration of this project (which Maven Repos is used and which version of Gradle is used ).
  • Files in the App subfolder. These files are typical gradle files used to create Android apps.
  • The files in the config sub-folder, the files here are the focus of our relationship, because I use the files here to save and configure all the tools in the project.
About Checkstyle

"Checkstyle is a development tool used to help programmers write Java code that complies with code specifications. It automatically checks Java code for idle people to perform this boring (but important) task ."

As the Checkstyle developer said, this tool can help you define and maintain a very precise and flexible code specification form in the project. When you start CheckStyle, it will analyze your Java code based on the provided configuration file and tell you all the errors found.

Gradle format

The following code shows you the most basic configurations for using Checkstyle in your project (such as Gradle tasks ):

task checkstyle(type: Checkstyle) {configFile file("${project.rootDir}/config/quality/checkstyle/checkstyle.xml") // Where my checkstyle config is...configProperties.checkstyleSuppressionsPath = file("${project.rootDir}/config/quality/checkstyle/suppressions.xml").absolutePath // Where is my suppressions file for checkstyle is...source 'src'include '**/*.java'exclude '**/gen/**'classpath = files()}

Therefore, this task will analyze your code based on checkstyle. xml and suppressions. xml. To execute it through Android Studio, you only need to start it from the CheckStyle of the tool.

After you start CheckStyle, you will receive a report to show every error found in your project. This is a very direct method.

For more configuration on checkstyle, refer to this document.

Tips for using Checkstyle

Checkstyle will find a lot of problems, especially when you use a lot of Rule configurations, as if you set a very accurate syntax. Although I use checkstyle through Gradle, for example, before I push, I still recommend that you use the checkstyle plug-in for intellij/Android Studio (you can directly install the plug-in through the work panel file/settings/plug-in of Android Studio ). In this way, you can use checkstyle in your project based on the same files configured for Gradle, but far more than that, you can directly obtain the results with hyperlinks in Android Studio, these results correspond in your code through hyperlinks, which is very useful (this method of Gradle is still very important, because you can use it to automatically build a system, such as Jenkins ).

About Findbugs

Does Findbugs need an introduction? I think its name is already the name of the person. "FindBugs uses static analysis to check Java bytecode in bug mode ". FindBugs basically only needs a program for analysis, so this is very easy to use. It can detect common errors, such as incorrect boolean operators. FindBugs can also detect errors due to incorrect language features, such as Java Parameter Adjustment (this is not true because its parameters are passed values ).

Gradle format

The following code shows you the most basic configuration for using Findbugs in your project (taking the Gradle task as an example ):

task findbugs(type: FindBugs) {ignoreFailures = falseeffort = "max"reportLevel = "high"excludeFilter = new File("${project.rootDir}/config/quality/findbugs/findbugs-filter.xml")classes = files("${project.rootDir}/app/build/classes")source 'src'include '**/*.java'exclude '**/gen/**'reports {xml.enabled = falsehtml.enabled = truexml {destination "$project.buildDir/reports/findbugs/findbugs.xml"}html {destination "$project.buildDir/reports/findbugs/findbugs.html"}}classpath = files()}

It is such a Checkstyle task. Although Findbugs supports both HTML and XML report formats, I chose the HTML format because it is more readable. In addition, you only need to set the report location as a bookmarks to quickly access its location. This task will also fail if the Findbgus error is found to fail (the report is also generated ). Execute a FindBugs task, just like executing a CheckStyle task (except the task name is "FindBugs ").

Tips for using Findbugs

Since the Android project is slightly different from the Java project, I strongly recommend using the FindBugs filter (rule configuration ). You can use this example (for example, one project ). It basically ignores the R file and your Manifest file. By the way, because (use) FindBugs analyzes your code, you must compile your code at least once to test it.

Overview

This tool has an interesting fact: there is no exact name for the PMD tool. (So) You can find interesting names on the official website, such:

  • Pretty Much Done
  • Project Meets Deadline

In fact, PMD is a powerful tool that works a bit like Findbugs, but (PMD) directly checks the source code rather than the bytecode (by the way, it applies to many languages ). (PMD and Findbugs) have the same core goal. They use static analysis to find out which modes cause bugs. So why are we using both Findbugs and PMD? Okay! Although Findbugs and PMD have the same goals, their check methods are different. Therefore, sometimes the bug detected by PMD is not detected by Findbugs, and vice versa.

Gradle format

The following code shows you the most basic configurations for using PMD in your project (take the Gradle task as an example ):

task pmd(type: Pmd) {ruleSetFiles = files("${project.rootDir}/config/quality/pmd/pmd-ruleset.xml")ignoreFailures = falseruleSets = []source 'src'include '**/*.java'exclude '**/gen/**'reports {xml.enabled = falsehtml.enabled = truexml {destination "$project.buildDir/reports/pmd/pmd.xml"}html {destination "$project.buildDir/reports/pmd/pmd.html"}}}

In terms of PMD, it is almost the same as Findbugs. PMD supports two reporting formats: HTML and XML, so I chose HTML again. I strongly recommend that you use your own general configuration set file, just as I did in this example (check this file. So, of course you should look at these general configuration set files. I suggest you, because it is much more controversial than FindBugs, for example, if you do not declare "if statement" or "if statement" to be empty, it will basically give you a warning. If these rules are correct, or this is true for your project (for example), I really agree with the work of you and your teammates. I don't want the program to crash because of the "if statement", so I think the program is quite readable. Execute a PMD task, such as a CheckStyle task (except the task name is "PMD ").

Tips for using PMD

I recommend that you do not use the default rule configuration set. You need to add this line of code (added ):

ruleSets = []

Otherwise, because the default value is the basic rule configuration set, the basic rule configuration set is executed together with the Rule Set you defined. Therefore, if your custom rule set is not in those basic configuration sets, they will still execute.

Introduction to Android Lint

"The Android lint tool is a static code analysis tool that can check the potential defects of the Android project source files and improve the correctness, security, performance, availability, accessibility and internationalization of the improvements ."

As the official website says, Android Lint is another static analysis tool dedicated to Android. It is very powerful and can give you a lot of suggestions to improve the quality of your code.

Gradle format
android {lintOptions {abortOnError truelintConfig file("${project.rootDir}/config/quality/lint/lint.xml")// if true, generate an HTML report (with issue explanations, sourcecode, etc)htmlReport true// optional path to report (default will be lint-results.html in the builddir)htmlOutput file("$project.buildDir/reports/lint/lint.html")}

I recommend that you use a separate file to define which configurations need to be used or are not used. This website defines all configurations based on the latest ADT version. The lint file in my demo project contains all these rules (ADT 21), including the "severity" with the "ignore" level ":

  • IconDensities: This rule configuration ensures that you define the (resolution) density (except ldpi) in each image resource ).
  • IconDipSize: This rule configuration ensures that you define the appropriate resources for each dip (in other words, if you do not set the same image resource for each density, you do not need to reset the image size ).

So you can reuse this lint file and activate all the rules you want. Running Android Lint tasks is like executing a CheckStyle task (except that the task name is "lint ").

Android Lint usage skills

There are no special skills for Android Lint. You just need to remember that Android Lint will test all the configuration rules except for the "severity" configurations with the "ignore" level. Therefore, if the new configuration rules under the new version of ADT are released, they will be checked, rather than ignored.

Instance demo

Currently, you have some ways to use these four tools for your project. Obviously, it would be better if we could use these four tools at the same time. You can add dependencies between your gradle tasks. For example, when you execute a task, other tasks are executed after the first task is completed. In Gradle, tools are usually interconnected by having a "check" task:

Check. dependsOn 'checkstyle', 'findbugs', 'vps', and 'lint'. Now, when you execute the "check" task, checkstyle, findbugs, pmd, and Android Lint will be executed at the same time. It is a great way to perform a quality check before you execute the/commiting/pushing/ask merge request.

You can find a complete example of all tasks in this Gradle file. You can separate all quality configuration files from Gradle files from the demo instances you see. These demo instances are put together in the "config/quality" folder.

Summary

In this article, it is very easy to use Gradle for Android code quality check tools. Compared to using quality tools to locally check your project on your own computer, these tools can be used to automatically build platforms such as Jenkins/Hudson, allowing you to perform automatic quality checks, automatic creation process. Execute all the tests I presented from CLI, just as on Jenkins/Hudson, simply execute:

Gradle check can post comments to this article at any time or ask any questions about Android.

How to improve quality and syntax of your Android code/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.