Home > Java > javaTutorial > 4 tools to improve Android code quality

4 tools to improve Android code quality

伊谢尔伦
Release: 2016-11-30 10:31:06
Original
1035 people have browsed it

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. Checking your code in an automated way is very useful, especially when you work in a team, in order to maintain strict syntax in your code and avoid many bad habits and mistakes. I'll walk through how to use these tools directly through Gradle build scripts at your leisure and how to configure them.

4 tools to improve Android code quality

 Fork this example

 I strongly recommend that you copy this project, although the cases I will introduce are all from it. In the meantime, you'll be able to test your knowledge of these tools.

About Gradle tasks

 The concept of Gradle tasks (the meaning in Gradle) is the basis for understanding this article (and how to write Gradle scripts in a common way). I strongly recommend you to read these two documents about Gradle tasks (this and this). This documentation contains lots of examples, so it's very easy to get started. Now, I assume that you copied my repo, that you imported the project into your Android Studio, and that you are familiar with Gradle tasks. If not, don't worry, I'll do my best to make my explanation more meaningful.

About the hierarchy of the sample project

You can split the gradle script file into many files, I already have 3 gradle files now:

Files in the root folder, these files are more or less about this project Configuration (which Maven Repos to use, which version of Gradle to use).

Files in the App subfolder, these files are typical gradle files used to create Android applications.

The files in the config subfolder, 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.

 Checkstyle

 Introduction

  "Checkstyle is a development tool used to help programmers write Java code that conforms to code specifications. It can automatically check Java code for people who are free to perform this boring (but important) task."

 As the developers of Checkstyle say, this tool can help you define and maintain a very precise and flexible code specification form in your project. When you start CheckStyle, it analyzes your Java code based on the provided configuration file and tells you any errors it finds.

Form of Gradle

The following code shows you the most basic configuration of using Checkstyle in your project (such as Gradle task):

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()
}
Copy after login

So, basically this task will be based on checkstyle.xml and suppressions.xml Analyze your code. Executing it through Android Studio simply requires launching it from the CheckStyle tool panel.

After launching CheckStyle, you will receive a report showing every error found in your project. This is a very direct way.

If you want to do more configuration on checkstyle, you can refer to this document.

 Checkstyle usage tips

  Checkstyle会发现大量的问题,特别是在你运用了大量的规则配置,如同你设置了一个非常精确的语法。尽管我通过Gradle使用 checkstyle,例如在我进行推送之前,我仍然推荐你为IntellJ/Android Studio使用checkstyle插件(你可以通过Android Studio的工作面板文件/设置/插件直接安装插件)。这种方式下,你可以根据那些为Gradle配置的相同文件在你的工程中使用 checkstyle,但是远不止这些,你可以直接在Android Studio中获取带有超链接结果,这些结果通过超链接在你的代码中对应,这是非常有用的(Gradle的这种方式仍然很重要的,因为你可以使用它自动构建系统,如Jenkins)。

 Findbugs

  简介

  Findbugs是否需要一个简介呢?我想它的名称已经让人顾名思义了。“FindBugs使用静态分析方法为出现bug模式检查Java字节码”。FindBugs基本上只需要一个程序来做分析的字节码,所以这是非常容易使用。它能检测到常见的错误,如错误的布尔运算符。FindBugs也能够检测到由于误解语言特点的错误,如Java参数调整(这不是真的有可能因为它的参数是传值)。

 Gradle的形式

  下面的代码向你展示了在你的项目中使用Findbugs的最基本的配置(以Gradle任务为例):

task findbugs(type: FindBugs) {
ignoreFailures = false
effort = "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 = false
html.enabled = true
xml {
destination "$project.buildDir/reports/findbugs/findbugs.xml"
}
html {
destination "$project.buildDir/reports/findbugs/findbugs.html"
}
}
 
classpath = files()
}
Copy after login

它是如此的像一个Checkstyle任务。尽管Findbugs支持HTML和XML两种报告形式,我选择HTML形式,因为这种形式更具有可读性。而且,你只需要把报告的位置设置为书签就可以快速访问它的位置。这个任务也会失败如果发现Findbgus错误失败(同样生成报告)。执行 FindBugs任务,就像执行CheckStyle任务(除了任务的名称是“FindBugs”)。

  Findbugs的使用技巧

  由于Android项目是从Java项目略有不同,我强烈推荐使用FindBugs过滤器(规则配置)。你可以在这一个例子(例如项目之一)。它基本上忽略了R文件和你的Manifest文件。顺便说一句,由于(使用)FindBugs分析你的代码,你至少需要编译一次你的代码才能够测试它。

 PMD

  简介

  这个工具有个有趣的事实:PMD不存在一个准确的名称。(所以)在官网上你可以发现很有有趣的名称,例如:

Pretty Much Done

Project Meets Deadline

  事实上,PMD是一个工作有点类似Findbugs的强大工具,但是(PMD)直接检查源代码而不是检查字节码(顺便说句,PMD适用很多语言)。 (PMD和Findbugs)的核心目标是相同的,通过静态分析方法找出哪些模式引起的bug。因此为什么同时使用Findbugs和PMD呢?好吧!尽管Findbugs和PMD拥有相同的目标,(但是)他们的检查方法是不同的。所以PMD有时检查出的bug但是Findbugs却检查不出来,反之亦然。

Gradle的形式

  下面的代码向你展示了在你的项目中使用PMD的最基本的配置(以Gradle任务为例):

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

 就PMD来说,它几乎与Findbugs相同。PMD支持HTML和XML两种报告形式,所以我再次选择HTML形式。我强烈建议你使用自己的通用配置集文件,正如同我在这个例子(check this file)中一样。所以,你当然应该去看下这些通用配置集文件。我建议你,因为PMD可比FindBugs更有争议的很多,例如:如果你不声明”if statement”或”if statement”为空,它基本上会给你警告信息。如果这些规则是正确的,或这对于您的项目(来说是正确的),我真的认可你和你队友的工作。我不希望程序因为”if statement”崩溃,我认为这样程序的可读性很差。执行PMD任务,就像是(执行)CheckStyle任务(除了任务的名称是“PMD”)。

  PMD的使用技巧

  我建议你不要使用默认的规则配置集,你需要添加这行代码(已经加上):

ruleSets = []
Copy after login


否则,因为默认值是这些基本的规则配置集,基本的规则配置集会和你定义的规则集一起执行。所以,如果你的自定义规则集不在那些基本配置集中,他们仍然会执行。

 Android Lint

  简介

  “Android lint工具是一个静态代码分析工具,它能检查安卓项目源文件的潜在缺陷和优化改进的正确性,安全性,性能,可用性,可访问性和国际化。”

 正如官方网站所说,Android Lint是另一种静态分析工具,专门为Android服务。它是非常强大的,能给你大量的建议以提高你的代码质量。

  Gradle的形式

android {
lintOptions {
abortOnError true
 
lintConfig 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")
}
Copy after login

 我建议你使用一个单独的文件来定义哪些配置需要使用和不使用。这个网站根据最新的ADT版本定义了全部的配置。我的演示项目中的lint文件包含所有这些规则(ADT 21),包含等级为”ignore”的”severity”:

IconDensities:这个规则配置确保你定义每个图像资源中的(分辨率)密度(除了ldpi)。

IconDipSize:这个规则配置确保你为每个dip定义合适的资源(换句话来说,如果你没有为每个density设置相同的图片资源,则不需要重新设置图片大小)。

  所以你可以重用这个lint文件并激活你想要的所有规则。执行Android Lint任务,就像执行CheckStyle任务(除了任务的名称是”lint”)。

  Android Lint的使用技巧

  对于Android Lint没有什么特别的技巧,只需要牢记Android Lint会测试所有配置规则,除了那些等级为“ignore”的“severity”的配置。因此如果发布了新版本ADT下的新配置规则,他们将被检查,而不是忽视。 

实例演示

  现在,你有所有的方法为您的项目使用这四个工具。显然,如果我们能同时使用这四个工具会更好。你可以添加你的gradle任务之间的依赖,比如当你执行一个任务,其他任务则是第一个完成后执行。通常在Gradle中,通过让工具具有“check”任务来达到工具之间的相互关系:

 check.dependsOn ‘checkstyle’, ‘findbugs’, ‘pmd’, ‘lint’ Now, when executing the “check” task, Checkstyle, Findbugs, PMD, and Android Lint will be executed at the same time. It's a great way to do a QA before you perform /commit / push / ask merge request.

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

 Summary

 In this article, it is very easy to use the code quality inspection tool for Android using Gradle. Rather than using quality tools to locally check your project on your own computer, these tools can be used to automate builds for platforms like Jenkins/Hudson, allowing you to automate quality checks while automating the build process. To execute all the tests I've exposed from the CLI as if they were executed on Jenkins/Hudson, simply execute:

  gradle check Please feel free to comment on this post or ask any Android-related questions.

  Original link: How to improve quality and syntax of your Android code


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template