# P3C-PMD
## <font color="green">Build requirements</font>
- JDK 1.7+
- Maven 3
## <font color="green">Use as dependency</font>
### <font color="green">Maven</font>
```xml
<dependency>
<groupId>com.alibaba.p3c</groupId>
<artifactId>p3c-pmd</artifactId>
<version>2.1.1</version>
</dependency>
```
### <font color="green">Gradle</font>
```groovy
compile 'com.alibaba.p3c:p3c-pmd:2.1.1'
```
## <font color="green">Rules</font>
P3C-PMD implements 54 rules involved in *Alibaba Java Coding Guidelines*, based on PMD ([https://github.com/pmd/pmd](https://github.com/pmd/pmd)).
### <font color="green">Concurrency</font>
* 1 ``[Mandatory]`` Customized ThreadLocal variables must be recycled, especially when using thread pools in which threads are often reused. Otherwise, it may affect subsequent business logic and cause unexpected problems such as memory leak.
* 2 ``[Mandatory]`` A meaningful thread name is helpful to trace the error information, so assign a name when creating threads or thread pools.
Positive example:
```java
public class TimerTaskThread extends Thread {
public TimerTaskThread(){
super.setName("TimerTaskThread"); … }
```
* 3 ``[Mandatory]`` Threads should be provided by thread pools. Explicitly creating threads is not allowed.
Note: Using thread pool can reduce the time of creating and destroying thread and save system resource. If we do not use thread pools, lots of similar threads will be created which lead to "running out of memory" or over-switching problems.
* 4 ``[Mandatory]`` A thread pool should be created by ThreadPoolExecutor rather than Executors. These would make the parameters of the thread pool understandable. It would also reduce the risk of running out of system resources.
Note: Below are the problems created by usage of Executors for thread pool creation:
1. FixedThreadPool and SingleThreadPool:
Maximum request queue size Integer.MAX_VALUE. A large number of requests might cause OOM.
2. CachedThreadPool and ScheduledThreadPool:
The number of threads which are allowed to be created is Integer.MAX_VALUE. Creating too many threads might lead to OOM.
* 5 ``[Mandatory]`` SimpleDataFormat is unsafe, do not define it as a static variable. If you have to, lock or Apache DateUtils class must be used.
Positive example: Pay attention to thread-safety when using DateUtils. It is recommended to use below:
```java
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
```
Note: In JDK8, Instant can be used to replace Date; likewise Calendar is replaced by LocalDateTime, and SimpleDateFormatter is replaced by DateTimeFormatter.
* 6 ``[Mandatory]`` Run multiple TimeTask by using ScheduledExecutorService rather than Timer, because Timer will kill all running threads in case of failure to catch exceptions.
* 7 ``[Recommended]`` When using CountDownLatch to convert asynchronous operations to synchronous ones, each thread must call countdown method before quitting. Make sure to catch any exception during thread running, to let countdown method be executed. If main thread cannot reach await method, program will return until timeout.
Note: Be careful, exception thrown by a child thread cannot be caught by main thread.
* 8 ``[Recommended]`` Avoid using Random instance by multiple threads. Although it is thread-safe, competition on the same seed will damage performance.
Note: Random instance includes instances of java.util.Random and Math.random().
Positive example:
After JDK7, ThreadLocalRandom API can be used directly. But before JDK7, instance needs to be created in each thread.
### <font color="green">Collection</font>
* 1 ``[Mandatory]`` Do not cast subList in class ArrayList, otherwise ClassCastException will be thrown: java.util.RandomAccessSubList cannot be cast to java.util.ArrayList.
Note: subList of ArrayList is an inner class, which is a view of ArrayList. All operations on the Sublist will affect the original list finally.
* 2 ``[Mandatory]`` When using subList, be careful while modifying the size of original list. It might cause ConcurrentModificationException when performing traversing, adding or deleting on the subList.
* 3 ``[Mandatory]`` Use toArray(T[] array) to convert list to array. The input array type should be the same with the list whose size is list.size().
Counter example: Do not use toArray method without arguments. Since the return type is Object[], ClassCastException will be thrown when casting it to a different array type.
Positive example:
```java
List<String> list = new ArrayList<String>(2);
list.add("guan");
list.add("bao");
String[] array = new String[list.size()];
array = list.toArray(array);
```
Note: When using toArray method with arguments, if input array size is not large enough, the method will re-assign the size internally, and then return the address of new array. If the size is larger than needed, the value of index[list.size()] will be set to null while other values remain the same. Defining an input with the same size of the list is recommended.
* 4 ``[Mandatory]`` Do not use methods which will modify the list after using Arrays.asList to convert array to list, otherwise methods like add/remove/clear will throw UnsupportedOperationException.
Note: The result of asList is the inner class of Arrays, which does not implement methods to modify itself. Arrays.asList is only a transferred interface, data inside which is stored as an array.
```java
String[] str = new String[] { "a", "b" };
List<String> list = Arrays.asList(str);
```
Case 1: list.add("c"); will throw a runtime exception.
Case 2: str[0]= "gujin"; list.get(0) will be modified.
* 5 ``[Mandatory]`` Do not remove or add elements to a collection in a foreach loop. Please use Iterator to remove an item. Iterator object should be synchronized when executing concurrent operations.
Counter example:
```java
List<String> a = new ArrayList<String>();
a.add("1");
a.add("2");
for (String temp : a) {
if ("1".equals(temp)) {
a.remove(temp);
}
}
```
Note: If you try to replace "1" with "2", you will get an unexpected result.
Positive example:
```java
Iterator<String> it = a.iterator();
while (it.hasNext()) {
String temp = it.next();
if (delete condition) {
it.remove();
}
}
```
* 6``[Recommended]`` Set a size when initializing a collection if possible.
Note: Better to use ArrayList(int initialCapacity) to initialize ArrayList.
### <font color="green">Naming Conventions</font>
* 1 ``[Mandatory]`` No identifier name should start or end with an underline or a dollar sign.
Counter example: _name / __name / $Object / name_ / name$ / Object$
* 2 ``[Mandatory]`` Using Chinese, Pinyin, or Pinyin-English mixed spelling in naming is strictly prohibited. Accurate English spelling and grammar will make the code readable, understandable, and maintainable.
Positive example: alibaba / taobao / youku / Hangzhou. In these cases, Chinese proper names in Pinyin are acceptable.
* 3 ``[Mandatory]`` Class names should be nouns in UpperCamelCase except domain models: DO, BO, DTO, VO, etc.
Positive example: MarcoPolo / UserDO / HtmlDTO / XmlService / TcpUdpDeal / TaPromotion
Counter example: macroPolo / UserDo / HTMLDto / XMLService / TCPUDPDeal / TAPromotion
* 4 ``[Mandatory]`` Method names, parameter names, member variable names, and local variable names should be written in lowerCamelCase.
Positive example: localValue / getHttpMessage() / inputUserId
* 5 ``[Mandatory]`` Constant variable names should be written in upper characters separated
没有合适的资源?快使用搜索试试~ 我知道了~
阿里巴巴 Java 编码指南 pmd 实现和 IDE 插件
共365个文件
java:91个
kt:90个
xml:89个
需积分: 5 0 下载量 119 浏览量
2023-10-26
15:05:24
上传
评论
收藏 3.8MB ZIP 举报
温馨提示
介绍 该项目由3部分组成: PMD 实施 IntelliJ IDEA 插件 Eclipse插件 规则 基于PMD实现了49条规则,更详细的信息请参考P3C-PMD文档。IDE 插件(IDEA 和 Eclipse)中实现了四个规则,如下所示: [Mandatory]禁止使用已弃用的类或方法。 注意:例如,应使用decode(String source, Stringencode)而不是已弃用的方法decode(StringencodeStr)。一旦接口被弃用,接口提供者就有义务提供新的接口。同时,客户端程序员有义务检查它的新实现是什么。 [Mandatory]接口或抽象类中的重写方法必须使用 @Override 注解进行标记。反例:对于 getObject() 和 get0bject(),第一个是字母“O”,第二个是数字“0”。为了准确判断覆盖是否成功,需要使用@Override注解。同时,一旦抽象类中的方法签名发生更改,实现类将立即报告编译时错误。 [Mandatory]静态字段或方法应直接通过其类名而不是其相应的对象名来引用。
资源推荐
资源详情
资源评论
收起资源包目录
阿里巴巴 Java 编码指南 pmd 实现和 IDE 插件 (365个子文件)
gradlew.bat 3KB
website.css 47B
StaticDescriptionTemplate.ftl 243B
blocker.gif 605B
critical.gif 219B
clear.gif 163B
.gitignore 886B
.gitignore 841B
.gitignore 834B
.gitignore 815B
.gitignore 352B
build.gradle 3KB
build.gradle 908B
build.gradle 824B
settings.gradle 40B
gradlew 6KB
gradle-wrapper.jar 58KB
FixClassTypeResolver.java 29KB
CommentsMustBeJavadocFormatRule.java 9KB
IbatisMethodQueryForListRule.java 9KB
AvoidManuallyCreateThreadRule.java 8KB
RemoveCommentedCodeRule.java 7KB
AbstractMethodOrInterfaceMethodMustUseJavadocRule.java 7KB
AvoidCallStaticSimpleDateFormatRule.java 7KB
EqualsAvoidNullRule.java 6KB
ThreadShouldSetNameRule.java 6KB
MethodTooLongRule.java 6KB
StringConcatRule.java 6KB
I18nResources.java 6KB
MethodReturnWrapperTypeRule.java 6KB
AvoidConcurrentCompetitionRandomRule.java 5KB
PojoMustOverrideToStringRule.java 5KB
ClassMustHaveAuthorRule.java 5KB
TransactionMustHaveRollbackRule.java 5KB
ThreadPoolCreationRule.java 5KB
UnsupportedExceptionWithModifyAsListRule.java 5KB
UndefineMagicConstantRule.java 5KB
ConcurrentExceptionWithModifyOriginSubListRule.java 4KB
ThreadLocalShouldRemoveRule.java 4KB
LowerCamelCaseVariableNamingRule.java 4KB
NodeUtils.java 4KB
UseQuietReferenceNotationRule.java 4KB
AvoidCommentBehindStatementRule.java 4KB
SwitchStatementRule.java 3KB
ClassCastExceptionWithToArrayRule.java 3KB
AbstractAliRule.java 3KB
DontModifyInForeachCircleRule.java 3KB
TestClassShouldEndWithTestNamingRule.java 3KB
UseRightCaseForDateFormatRule.java 3KB
ConstantFieldShouldBeUpperCaseRule.java 3KB
WrapperTypeEqualityRule.java 3KB
CollectionInitShouldAssignCapacityRule.java 3KB
BigDecimalAvoidDoubleConstructorRule.java 3KB
EnumConstantsMustHaveCommentRule.java 3KB
ExtendRuleTst.java 3KB
NeedBraceRule.java 3KB
PojoMustUsePrimitiveFieldRule.java 3KB
PojoNoDefaultValueRule.java 3KB
NameListServiceImpl.java 3KB
CountDownShouldInFinallyRule.java 2KB
AvoidStartWithDollarAndUnderLineNamingRule.java 2KB
ExceptionClassShouldEndWithExceptionRule.java 2KB
AvoidPatternCompileInMethodRule.java 2KB
ClassNamingShouldBeCamelRule.java 2KB
ViolationUtils.java 2KB
ClassCastExceptionWithSubListToArrayListRule.java 2KB
BooleanPropertyShouldNotStartWithIsRule.java 2KB
AbstractPojoRule.java 2KB
AvoidUseTimerRule.java 2KB
GeneratedCodeUtils.java 2KB
AbstractClassShouldStartWithAbstractNamingRule.java 2KB
ServiceOrDaoClassShouldEndWithImplRule.java 2KB
AvoidMissUseOfMathRandomRule.java 2KB
AvoidNewDateGetTimeRule.java 2KB
AvoidComplexConditionRule.java 2KB
AvoidNegationOperatorRule.java 2KB
AbstractAliCommentRule.java 2KB
NamingRulesTest.java 2KB
AbstractXpathRule.java 2KB
PackageNamingRule.java 2KB
ArrayNamingShouldHaveBracketRule.java 2KB
SpiLoader.java 2KB
AvoidReturnInFinallyRule.java 2KB
AvoidDoubleOrFloatEqualCompareRule.java 2KB
UpperEllRule.java 2KB
AvoidApacheBeanUtilsCopyRule.java 2KB
UseRightCaseForDateFormatRuleExam.java 1KB
PojoUtils.java 1KB
ConcurrentRuleTest.java 1KB
NodeSortUtils.java 1KB
OtherRulesTest.java 1KB
OopRuleTest.java 1KB
SetRulesTest.java 1KB
CommentRulesTest.java 1KB
P3cIcons.java 1KB
NameListService.java 1KB
NumberConstants.java 1KB
FlowControlRuleTest.java 1KB
ExceptionRulesTest.java 1KB
NameListConfig.java 1KB
共 365 条
- 1
- 2
- 3
- 4
资源评论
Web面试那些事儿
- 粉丝: 4930
- 资源: 101
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功