您的位置:首页 > 编程语言 > Java开发

JAVA应用技术之编码规范(codetemplate,checkstyle)

2012-02-13 10:02 351 查看
1.CodeTemplate模板

在日常开发代码的过程中,我们往往需要一个编码规范,比如注释规范,不然,每个人写得不一样,不利于公司资产或者说代码库管理,让后期代码维护造成很大影响。下面我根据我们公司给的那个JAVA编码规范制作成一个codetemplate模板供大家参考,下面是它的代码内容,稍后我来说明如何将其将入eclipse代码库中。

下面是我配置后导出的codetemplate.xml,仅供参考:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<templates>

<template autoinsert="false" context="gettercomment_context"

deleted="false" description="Comment for getter method" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.gettercomment" name="gettercomment">/**

*

${bare_field_name}

* @return the ${bare_field_name}

*/

</template>

<template autoinsert="false" context="settercomment_context"

deleted="false" description="Comment for setter method" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.settercomment" name="settercomment">/**

*

@param ${param} 要设置的 ${bare_field_name}

**/</template>

<template autoinsert="false" context="constructorcomment_context"

deleted="false" description="Comment for created constructors"

enabled="true" id="org.eclipse.jdt.ui.text.codetemplates.constructorcomment"

name="constructorcomment">/**

* <p>Title: </p>

* <p>Description: </p>

* ${tags}

*/</template>

<template autoinsert="false" context="filecomment_context"

deleted="false" description="Comment for created Java files" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.filecomment" name="filecomment">

/*

* Copyright (C) 2011 GZ-ISCAS Inc., All Rights Reserved.

*/</template>

<template autoinsert="false" context="typecomment_context"

deleted="false" description="Comment for created types" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.typecomment" name="typecomment">/**

* @ClassName: ${type_name}

* @Description: ${todo}(这里用一句话描述这个类的作用)

* @author ????? Email: ??????@gz.iscas.ac.cn

* @date ${date} - ${time}

*@version : 1.0

* ${tags}

*/</template>

<template autoinsert="false" context="fieldcomment_context"

deleted="false" description="Comment for fields" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.fieldcomment" name="fieldcomment">/**

* @Fields ${field} : ${todo}(用一句话描述这个变量表示什么)

*/</template>

<template autoinsert="false" context="methodcomment_context"

deleted="false" description="Comment for non-overriding methods"

enabled="true" id="org.eclipse.jdt.ui.text.codetemplates.methodcomment"

name="methodcomment">/**

* @Title: ${enclosing_method}

* @Description: ${todo}(这里用一句话描述这个方法的作用)

* @param ${tags} 设定文件

* @return ${return_type} 返回类型

* @throws

*/</template>

<template autoinsert="false" context="overridecomment_context"

deleted="false" description="Comment for overriding methods" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.overridecomment" name="overridecomment">/* (非

Javadoc)

* <p>Title: ${enclosing_method}</p>

* <p>Description: </p>

* ${tags}

* ${see_to_overridden}

*/</template>

<template autoinsert="false" context="delegatecomment_context"

deleted="false" description="Comment for delegate methods" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.delegatecomment" name="delegatecomment">/**

*

${tags}

* ${see_to_target}

*/</template>

<template autoinsert="true" context="newtype_context" deleted="false"

description="Newly created files" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.newtype" name="newtype">${filecomment}

${package_declaration}

${typecomment}

${type_declaration}</template>

<template autoinsert="true" context="classbody_context"

deleted="false" description="Code in new class type bodies" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.classbody" name="classbody">

</template>

<template autoinsert="true" context="interfacebody_context"

deleted="false" description="Code in new interface type bodies"

enabled="true" id="org.eclipse.jdt.ui.text.codetemplates.interfacebody"

name="interfacebody">

</template>

<template autoinsert="true" context="enumbody_context"

deleted="false" description="Code in new enum type bodies" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.enumbody" name="enumbody">

</template>

<template autoinsert="true" context="annotationbody_context"

deleted="false" description="Code in new annotation type bodies"

enabled="true" id="org.eclipse.jdt.ui.text.codetemplates.annotationbody"

name="annotationbody">

</template>

<template autoinsert="true" context="catchblock_context"

deleted="false" description="Code in new catch blocks" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.catchblock" name="catchblock">// ${todo}

Auto-generated catch block

${exception_var}.printStackTrace();</template>

<template autoinsert="true" context="methodbody_context"

deleted="false" description="Code in created method stubs" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.methodbody" name="methodbody">// ${todo}

Auto-generated method stub

${body_statement}</template>

<template autoinsert="true" context="constructorbody_context"

deleted="false" description="Code in created constructor stubs"

enabled="true" id="org.eclipse.jdt.ui.text.codetemplates.constructorbody"

name="constructorbody">${body_statement}

// ${todo} Auto-generated constructor stub</template>

<template autoinsert="true" context="getterbody_context"

deleted="false" description="Code in created getters" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.getterbody" name="getterbody">return

${field};</template>

<template autoinsert="true" context="setterbody_context"

deleted="false" description="Code in created setters" enabled="true"

id="org.eclipse.jdt.ui.text.codetemplates.setterbody" name="setterbody">${field} =

${param};</template>

</templates>

复制代码

导入的时候打开eclipse,在windows菜单下选中Preferences,打开如下对话框,



这样就先成导入模板操作了。

2.使用checkstyle插件

安装过程略,详细查看杰哥的PPT文档,下面说一下如何配置和使用checkstyle插件。

参考网上,并参照JAVA规范,如下所示:

checkstyle.xml文件:

<?xml version="1.0" encoding="UTF-8"?>

<!--

/*

* Copyright 2001-2004 The Apache Software Foundation.

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0
*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

-->

<!DOCTYPE module PUBLIC

"-//Puppy Crawl//DTD Check Configuration 1.1//EN"

"http://www.puppycrawl.com/dtds/configuration_1_1.dtd">

<module name="Checker">

<!--

javadoc部分的检测都属于第二等级,建议使用。

-->

<module name="PackageHtml">

<property name="severity" value="warning"/>

</module>

<!--

每个源文件的结尾,必须有一个空行。

这部分由代码美化器控制。

<module name="NewlineAtEndOfFile"/>

-->

<!--

翻译

-->

<module name="Translation"/>

<module name="TreeWalker">

<property name="cacheFile" value="${checkstyle.cache.file}"/>

<property name="tabWidth" value="4"/>

<!--

Javadoc comments

javadoc部分的检测都属于第二等级,建议使用。

-->

<module name="JavadocMethod">

<property name="severity" value="warning"/>

</module>

<module name="JavadocType">

<property name="severity" value="warning"/>

</module>

<module name="JavadocVariable">

<property name="severity" value="warning"/>

</module>

<module name="JavadocStyle">

<property name="severity" value="warning"/>

</module>

<!--

Naming conventions

命名方式属于第一等级,一定要保证统一的命名格式。

-->

<module name="MemberName" />

<module name="ConstantName"/>

<module name="LocalFinalVariableName"/>

<module name="LocalVariableName"/>

<module name="MethodName"/>

<module name="PackageName"/>

<module name="ParameterName"/>

<module name="StaticVariableName"/>

<module name="TypeName"/>

<!--

Headers

-->

<!--

Imports

强制要求import不能使用*,不能使用sun开头的包,不能重复import,也不能有没用到的包。

-->

<module name="AvoidStarImport"/>

<module name="IllegalImport"/>

<module name="RedundantImport"/>

<module name="UnusedImports"/>

<!--

Size Violations

每行不得超过120个字符,@version和@see部分除外,这两部分有可能超过120个字符。

文件长度不能超过2000,方法长度不能超过150,内部类不能超过20行,方法的参数不能多于7个。

这几个也属于建议级别。

-->

<module name="LineLength">

<property name="max" value="120" />

<property name="ignorePattern" value="@version|@see"/>

</module>

<module name="FileLength">

<property name="severity" value="warning"/>

</module>

<module name="MethodLength">

<property name="severity" value="warning"/>

</module>

<module name="ParameterNumber">

<property name="severity" value="warning"/>

</module>

<module name="AnonInnerLength">

<property name="severity" value="warning"/>

</module>

<!--

Whitespace

for循环的空白,用空白包裹操作符,不允许使用\t制表符

使用代码美化器实现,这些是必须遵守的。

-->

<module name="EmptyForIteratorPad"/>

<module name="OperatorWrap"/>

<module name="ParenPad"/>

<module name="TabCharacter"/>

<module name="MethodParamPad"/>

<!--

Modifiers

修饰符必须按顺序排列,不允许重复。

-->

<module name="ModifierOrder"/>

<module name="RedundantModifier"/>

<!--

Block checks

禁止出现块嵌套,if,else即使只有一行数据,也要写上大括号。

emptyblock可以提醒开发者,不要忘记实现block中的内容。

-->

<module name="LeftCurly"/>

<module name="RightCurly"/>

<module name="AvoidNestedBlocks"/>

<module name="EmptyBlock"/>

<module name="NeedBraces">

<property name="tokens" value="LITERAL_IF, LITERAL_ELSE"/>

</module>

<!--

Coding

不要重复检测同一条件,不能用空的语句,检测equals和hashcode配对,

除了setter和constructor其他方法的参数和类变量不能同名,

不能使用性能不高的初始化方法,不能在参数表中使用赋值语句,

不能使用无法确定含义的数字,除了-1,0,1,2以外,

switch必须包含default,使用简单boolean表达式和返回表达式。

-->

<module name="DoubleCheckedLocking"/>

<module name="EmptyStatement"/>

<module name="EqualsHashCode"/>

<module name="HiddenField">

<property name="ignoreConstructorParameter" value="true"/>

<property name="ignoreSetter" value="true"/>

</module>

<module name="IllegalInstantiation"/>

<module name="InnerAssignment"/>

<module name="MagicNumber"/>

<module name="MissingSwitchDefault"/>

<module name="RedundantThrows"/>

<module name="SimplifyBooleanExpression"/>

<module name="SimplifyBooleanReturn"/>

<!--

Class Design

interface中必须定义方法,不能只有变量。

-->

<module name="FinalClass"/>

<module name="HideUtilityClassConstructor"/>

<module name="InterfaceIsType"/>

<module name="VisibilityModifier">

<property name="protectedAllowed" value="true"/>

</module>

<!--

Duplicate code

-->

<!--

Metrics

DAC不大于7,

CFO不大于20,

CC不大于10,

NPath不大于200,

布尔表达式,运算符不超过3个

-->

<module name="ClassDataAbstractionCoupling">

<property name="severity" value="info"/>

</module>

<module name="ClassFanOutComplexity">

<property name="severity" value="info"/>

</module>

<module name="CyclomaticComplexity">

<property name="severity" value="info"/>

</module>

<module name="NPathComplexity">

<property name="severity" value="info"/>

</module>

<module name="BooleanExpressionComplexity">

<property name="severity" value="info"/>

</module>

<!--

Miscellaneous other checks.

行末不能有空格,符合TODO:形式的注释会被提示出来

用于测试的main函数(没有注释),应该删除

定义long应该使用“L”而不是“l”

使用java格式的数组类型定义

-->

<module name="ArrayTypeStyle"/>

<module name="GenericIllegalRegexp">

<property name="format" value="\s+[ DISCUZ_CODE_1 ]quot;/>

<property name="message" value="Line has trailing spaces."/>

</module>

<module name="TodoComment"/>

<module name="UpperEll"/>

<module name="UncommentedMain"/>

</module>

</module>

复制代码

然后在顶级pom.xml文件中加入如下代码:

下面这个是打印报表所需要的插件配置。

<reporting>

<plugins>

<plugin>

<groupId>org.codehaus.mojo</groupId>

<artifactId>cobertura-maven-plugin</artifactId>

<version>2.4</version>

<inherited>true</inherited>

</plugin>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-javadoc-plugin</artifactId>

<version>2.6.1</version>

<configuration>

<encoding>UTF-8</encoding>

</configuration>

<inherited>true</inherited>

</plugin>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-checkstyle-plugin</artifactId>

<version>2.8</version>

<configuration>

<configLocation>F:/project/sems/cn.ac.iscas.gz.sems/checkstyle.xml</configLocation>

<headerLocation>../LICENSE.txt</headerLocation>

</configuration>

</plugin>

</plugins>

</reporting>

复制代码

然后是<plugins>插件的配置.

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-checkstyle-plugin</artifactId>

<version>2.8</version>

<dependencies>

<dependency>

<groupId>com.example.whizbang</groupId>

<artifactId>build-tools</artifactId>

<version>1.0</version>

</dependency>

</dependencies>

</plugin>

</plugins>

复制代码

最后在命令行中输入

mvn
site 或者 mvn
compile checkstyle:checkstyle

如果你要撤销的话,用 mvn clean site

这样就会在target\site 下面生成报表文件,如下所示:



3.一些理论知识

Checkstyle是一个开发工具,可以帮助编程人员编写符合编码规范的java
代码。程序员都非常讨厌程序的check工作,checkstyle能够自动地完成这项烦琐但又非常重要的工作,从而节省了的程序员的时间,也提高了检查的质量。Checkstyle已经成了加强编码规范的首选工具。

(完,待续....)

参考网址:
http://code.google.com/p/testcq/wiki/CheckStyleRules

http://maven.apache.org/plugins/maven-checkstyle-plugin/examples/multi-module-config.html

/article/3891086.html

/article/3848135.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: