骏烈 7 years ago
parent 1ade912a4e
commit 40eaededd1

@ -61,7 +61,7 @@ object CodeAnalysis {
if (monitor.isCanceled) { if (monitor.isCanceled) {
return@run Status.CANCEL_STATUS return@run Status.CANCEL_STATUS
} }
if(it.isAccessible){ if (it.isAccessible) {
it.accept(fileVisitor) it.accept(fileVisitor)
} }
} }

@ -28,31 +28,31 @@ P3C-PMD implements 49 rules involved in *Alibaba Java Coding Guidelines*, based
* 2 ``[Mandatory]`` A meaningful thread name is helpful to trace the error information, so assign a name when creating threads or thread pools. * 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: Positive example:
```java ```java
public class TimerTaskThread extends Thread { public class TimerTaskThread extends Thread {
public TimerTaskThread(){ public TimerTaskThread(){
super.setName("TimerTaskThread"); … } super.setName("TimerTaskThread"); … }
``` ```
* 3 ``[Mandatory]`` Threads should be provided by thread pools. Explicitly creating threads is not allowed. * 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. 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. * 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: Note: Below are the problems created by usage of Executors for thread pool creation:
1. FixedThreadPool and SingleThreadPool: 1. FixedThreadPool and SingleThreadPool:
Maximum request queue size Integer.MAX_VALUE. A large number of requests might cause OOM. Maximum request queue size Integer.MAX_VALUE. A large number of requests might cause OOM.
2. CachedThreadPool and ScheduledThreadPool: 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. 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. * 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: Positive example: Pay attention to thread-safety when using DateUtils. It is recommended to use below:
```java ```java
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() { private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
@Override @Override
protected DateFormat initialValue() { protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd"); 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. 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. * 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. * 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. Note: Be careful, exception thrown by a child thread cannot be caught by main thread.
@ -70,48 +70,48 @@ Note: subList of ArrayList is an inner class, which is a view of ArrayList. All
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. 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: Positive example:
```java ```java
List<String> list = new ArrayList<String>(2); List<String> list = new ArrayList<String>(2);
list.add("guan"); list.add("guan");
list.add("bao"); list.add("bao");
String[] array = new String[list.size()]; String[] array = new String[list.size()];
array = list.toArray(array); 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. 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. * 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. 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 ```java
String[] str = new String[] { "a", "b" }; String[] str = new String[] { "a", "b" };
List<String> list = Arrays.asList(str); List<String> list = Arrays.asList(str);
``` ```
Case 1: list.add("c"); will throw a runtime exception. Case 1: list.add("c"); will throw a runtime exception.
Case 2: str[0]= "gujin"; list.get(0) will be modified. 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. * 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: Counter example:
```java ```java
List<String> a = new ArrayList<String>(); List<String> a = new ArrayList<String>();
a.add("1"); a.add("1");
a.add("2"); a.add("2");
for (String temp : a) { for (String temp : a) {
if ("1".equals(temp)){ if ("1".equals(temp)) {
a.remove(temp); a.remove(temp);
} }
} }
``` ```
Note: If you try to replace "1" with "2", you will get an unexpected result. Note: If you try to replace "1" with "2", you will get an unexpected result.
Positive example: Positive example:
```java ```java
Iterator<String> it = a.iterator(); Iterator<String> it = a.iterator();
while (it.hasNext()) { while (it.hasNext()) {
String temp = it.next(); String temp = it.next();
if (delete condition) { if (delete condition) {
it.remove(); it.remove();
} }
} }
``` ```
* 6``[Recommended]`` Set a size when initializing a collection if possible. * 6``[Recommended]`` Set a size when initializing a collection if possible.
Note: Better to use ArrayList(int initialCapacity) to initialize ArrayList. Note: Better to use ArrayList(int initialCapacity) to initialize ArrayList.
@ -145,9 +145,9 @@ Counter example: boolean isSuccess; The method name will be isSuccess() and then
* 9 ``[Mandatory]`` Package should be named in lowercase characters. There should be only one English word after each dot. Package names are always in singular format while class name can be in plural format if necessary. * 9 ``[Mandatory]`` Package should be named in lowercase characters. There should be only one English word after each dot. Package names are always in singular format while class name can be in plural format if necessary.
Positive example: com.alibaba.open.util can be used as package name for utils; Positive example: com.alibaba.open.util can be used as package name for utils;
* 10 There are mainly two rules for interface and corresponding implementation class naming: * 10 There are mainly two rules for interface and corresponding implementation class naming:
1. ``[Mandatory]`` All Service and DAO classes must be interface based on SOA principle. Implementation class names should be ended with Impl. 1. ``[Mandatory]`` All Service and DAO classes must be interface based on SOA principle. Implementation class names should be ended with Impl.
Positive example: CacheServiceImpl to implement CacheService. Positive example: CacheServiceImpl to implement CacheService.
2. ``[Recommended]`` If the interface name is to indicate the ability of the interface, then its name should be adjective. 2. ``[Recommended]`` If the interface name is to indicate the ability of the interface, then its name should be adjective.
Positive example: AbstractTranslator to implement Translatable. Positive example: AbstractTranslator to implement Translatable.
### <font color="green">Constant Conventions</font> ### <font color="green">Constant Conventions</font>
@ -167,9 +167,9 @@ Note: java.util.Objects#equals (a utility class in JDK7) is recommended.
* 5 ``[Mandatory]`` The wrapper classes should be compared by equals method rather than by symbol of '==' directly. * 5 ``[Mandatory]`` The wrapper classes should be compared by equals method rather than by symbol of '==' directly.
Note: Consider this assignment: Integer var = ?. When it fits the range from -128 to 127, we can use == directly for a comparison. Because the Integer object will be generated by IntegerCache.cache, which reuses an existing object. Nevertheless, when it fits the complementary set of the former range, the Integer object will be allocated in Heap, which does not reuse an existing object. This is an [implementation-level detail](https://docs.oracle.com/javase/specs/jls/se9/html/jls-5.html#jls-5.1.7-300) that should NOT be relied upon. Hence using the equals method is always recommended. Note: Consider this assignment: Integer var = ?. When it fits the range from -128 to 127, we can use == directly for a comparison. Because the Integer object will be generated by IntegerCache.cache, which reuses an existing object. Nevertheless, when it fits the complementary set of the former range, the Integer object will be allocated in Heap, which does not reuse an existing object. This is an [implementation-level detail](https://docs.oracle.com/javase/specs/jls/se9/html/jls-5.html#jls-5.1.7-300) that should NOT be relied upon. Hence using the equals method is always recommended.
* 6 ``[Mandatory]`` Rules for using primitive data types and wrapper classes: * 6 ``[Mandatory]`` Rules for using primitive data types and wrapper classes:
1. Members of a POJO class must be wrapper classes. 1. Members of a POJO class must be wrapper classes.
2. The return value and arguments of a RPC method must be wrapper classes. 2. The return value and arguments of a RPC method must be wrapper classes.
3. ``[Recommended]`` Local variables should be primitive data types. 3. ``[Recommended]`` Local variables should be primitive data types.
Note: In order to remind the consumer of explicit assignments, there are no initial values for members in a POJO class. As a consumer, you should check problems such as NullPointerException and warehouse entries for yourself. Note: In order to remind the consumer of explicit assignments, there are no initial values for members in a POJO class. As a consumer, you should check problems such as NullPointerException and warehouse entries for yourself.
Positive example: As the result of a database query may be null, assigning it to a primitive date type will cause a risk of NullPointerException because of Unboxing. Positive example: As the result of a database query may be null, assigning it to a primitive date type will cause a risk of NullPointerException because of Unboxing.
Counter example: Consider the output of a transaction volume's amplitude, like ±x%. As a primitive data, when it comes to a failure of calling a RPC service, the default return value: 0% will be assigned, which is not correct. A hyphen like - should be assigned instead. Therefore, the null value of a wrapper class can represent additional information, such as a failure of calling a RPC service, an abnormal exit, etc. Counter example: Consider the output of a transaction volume's amplitude, like ±x%. As a primitive data, when it comes to a failure of calling a RPC service, the default return value: 0% will be assigned, which is not correct. A hyphen like - should be assigned instead. Therefore, the null value of a wrapper class can represent additional information, such as a failure of calling a RPC service, an abnormal exit, etc.
@ -178,56 +178,56 @@ Note: In order to remind the consumer of explicit assignments, there are no init
Note: We can call the toString method in a POJO directly to print property values in order to check the problem when a method throws an exception in runtime. Note: We can call the toString method in a POJO directly to print property values in order to check the problem when a method throws an exception in runtime.
* 9 ``[Recommended]`` Use the append method in StringBuilder inside a loop body when concatenating multiple strings. * 9 ``[Recommended]`` Use the append method in StringBuilder inside a loop body when concatenating multiple strings.
Counter example: Counter example:
```java ```java
String str = "start"; String str = "start";
for(int i=0; i<100; i++) { for(int i=0; i<100; i++) {
str = str + "hello"; str = str + "hello";
} }
``` ```
Note: According to the decompiled bytecode file, for each iteration, it allocates a new StringBuilder object, appends a string, and finally returns a String object via the toString method. This is a tremendous waste of memory, especially when the iteration count is large. Note: According to the decompiled bytecode file, for each iteration, it allocates a new StringBuilder object, appends a string, and finally returns a String object via the toString method. This is a tremendous waste of memory, especially when the iteration count is large.
### <font color="green">Flow Control Statements</font> ### <font color="green">Flow Control Statements</font>
* 1 ``[Mandatory]`` In a switch block, each case should be finished by break/return. If not, a note should be included to describe at which case it will stop. Within every switch block, a default statement must be present, even if it is empty. * 1 ``[Mandatory]`` In a switch block, each case should be finished by break/return. If not, a note should be included to describe at which case it will stop. Within every switch block, a default statement must be present, even if it is empty.
* 2 ``[Mandatory]`` Braces are used with if, else, for, do and while statements, even if the body contains only a single statement. Avoid using the following example: * 2 ``[Mandatory]`` Braces are used with if, else, for, do and while statements, even if the body contains only a single statement. Avoid using the following example:
```java ```java
if (condition) statements; if (condition) statements;
``` ```
* 3 ``[Recommended]`` Do not use complicated expressions in conditional statements (except for frequently used methods like getXxx/isXxx). Using boolean variables to store results of complicated expressions temporarily will increase the code's readability. * 3 ``[Recommended]`` Do not use complicated expressions in conditional statements (except for frequently used methods like getXxx/isXxx). Using boolean variables to store results of complicated expressions temporarily will increase the code's readability.
Note: Logic within many if statements are very complicated. Readers need to analyze the final results of the conditional expression to understand the branching logic. Note: Logic within many if statements are very complicated. Readers need to analyze the final results of the conditional expression to understand the branching logic.
Positive example: Positive example:
```java ```java
// please refer to the pseudo-code as follows // please refer to the pseudo-code as follows
boolean existed = (file.open(fileName, "w") != null) && (...) || (...); boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
if (existed) { if (existed) {
... //...
} }
``` ```
Counter example: Counter example:
```java ```java
if ((file.open(fileName, "w") != null) && (...) || (...)) { if ((file.open(fileName, "w") != null) && (...) || (...)) {
... // ...
} }
``` ```
### <font color="green">Exception</font> ### <font color="green">Exception</font>
* 4 ``[Mandatory]`` Make sure to invoke the rollback if a method throws an Exception. Rollbacks are based on the context of the coding logic. * 4 ``[Mandatory]`` Make sure to invoke the rollback if a method throws an Exception. Rollbacks are based on the context of the coding logic.
* 5 ``[Mandatory]`` Never use return within a finally block. A return statement in a finally block will cause exceptions or result in a discarded return value in the try-catch block. * 5 ``[Mandatory]`` Never use return within a finally block. A return statement in a finally block will cause exceptions or result in a discarded return value in the try-catch block.
* 6 ``[Recommended]`` One of the most common errors is NullPointerException. Pay attention to the following situations: * 6 ``[Recommended]`` One of the most common errors is NullPointerException. Pay attention to the following situations:
* 1 If the return type is primitive, return a value of wrapper class may cause NullPointerException. * 1 If the return type is primitive, return a value of wrapper class may cause NullPointerException.
Counter example: public int f() { return Integer } Unboxing a null value will throw a NullPointerException. Counter example: public int f() { return Integer } Unboxing a null value will throw a NullPointerException.
* 2 The return value of a database query might be null. * 2 The return value of a database query might be null.
* 3 Elements in collection may be null, even though Collection.isEmpty() returns false. * 3 Elements in collection may be null, even though Collection.isEmpty() returns false.
* 4 Return values from an RPC might be null. * 4 Return values from an RPC might be null.
* 5 Data stored in sessions might by null. * 5 Data stored in sessions might by null.
* 6 Method chaining, like obj.getA().getB().getC(), is likely to cause NullPointerException. * 6 Method chaining, like obj.getA().getB().getC(), is likely to cause NullPointerException.
Positive example: Use Optional to avoid null check and NPE (Java 8+). Positive example: Use Optional to avoid null check and NPE (Java 8+).
### <font color="green">Code Comments</font> ### <font color="green">Code Comments</font>
* 1 ``[Mandatory]`` Javadoc should be used for classes, class variables and methods. The format should be '/** comment **/', rather than '// xxx'. * 1 ``[Mandatory]`` Javadoc should be used for classes, class variables and methods. The format should be '/** comment **/', rather than '// xxx'.

@ -25,15 +25,15 @@ import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper;
* @date 2016/11/16 * @date 2016/11/16
*/ */
public class NodeUtils { public class NodeUtils {
public static boolean isParentOrSelf(Node descendant,Node ancestor){ public static boolean isParentOrSelf(Node descendant, Node ancestor) {
if(descendant == ancestor) { if (descendant == ancestor) {
return true; return true;
} }
if(descendant == null || ancestor == null){ if (descendant == null || ancestor == null) {
return false; return false;
} }
Node parent = descendant.jjtGetParent(); Node parent = descendant.jjtGetParent();
while(parent != ancestor && parent != null){ while (parent != ancestor && parent != null) {
parent = parent.jjtGetParent(); parent = parent.jjtGetParent();
} }
return parent == ancestor; return parent == ancestor;
@ -41,18 +41,19 @@ public class NodeUtils {
/** /**
* TODO optimize * TODO optimize
*
* @param expression expression * @param expression expression
* @return true if wrapper type * @return true if wrapper type
*/ */
public static boolean isWrapperType(ASTPrimaryExpression expression) { public static boolean isWrapperType(ASTPrimaryExpression expression) {
return TypeHelper.isA(expression, Integer.class) return TypeHelper.isA(expression, Integer.class)
|| TypeHelper.isA(expression, Long.class) || TypeHelper.isA(expression, Long.class)
|| TypeHelper.isA(expression, Boolean.class) || TypeHelper.isA(expression, Boolean.class)
|| TypeHelper.isA(expression, Byte.class) || TypeHelper.isA(expression, Byte.class)
|| TypeHelper.isA(expression, Double.class) || TypeHelper.isA(expression, Double.class)
|| TypeHelper.isA(expression, Short.class) || TypeHelper.isA(expression, Short.class)
|| TypeHelper.isA(expression, Float.class) || TypeHelper.isA(expression, Float.class)
|| TypeHelper.isA(expression, Character.class); || TypeHelper.isA(expression, Character.class);
} }
public static boolean isConstant(ASTFieldDeclaration field) { public static boolean isConstant(ASTFieldDeclaration field) {

@ -27,8 +27,8 @@ Positive example 2
//Common Thread Pool //Common Thread Pool
ExecutorService pool = new ThreadPoolExecutor(5, 200, ExecutorService pool = new ThreadPoolExecutor(5, 200,
0L, TimeUnit.MILLISECONDS, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
pool.execute(()-> System.out.println(Thread.currentThread().getName())); pool.execute(()-> System.out.println(Thread.currentThread().getName()));
pool.shutdown();//gracefully shutdown pool.shutdown();//gracefully shutdown
@ -63,7 +63,7 @@ Positive example 3
<![CDATA[ <![CDATA[
//org.apache.commons.lang3.concurrent.BasicThreadFactory //org.apache.commons.lang3.concurrent.BasicThreadFactory
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build()); new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
executorService.scheduleAtFixedRate(new Runnable() { executorService.scheduleAtFixedRate(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -84,9 +84,9 @@ Positive example 3
<example> <example>
<![CDATA[ <![CDATA[
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("demo-pool-%d").build(); .setNameFormat("demo-pool-%d").build();
ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1, ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName())); singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName()));
@ -104,9 +104,9 @@ Positive example 3
<example> <example>
<![CDATA[ <![CDATA[
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("demo-pool-%d").build(); .setNameFormat("demo-pool-%d").build();
ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1, ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName())); singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName()));

@ -1,52 +1,52 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<ruleset name="AlibabaJavaConstants" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0" <ruleset name="AlibabaJavaConstants" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd"> xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<rule name="UpperEllRule" <rule name="UpperEllRule"
message="java.constant.UpperEllRule.rule.msg" message="java.constant.UpperEllRule.rule.msg"
class="com.alibaba.p3c.pmd.lang.java.rule.constant.UpperEllRule"> class="com.alibaba.p3c.pmd.lang.java.rule.constant.UpperEllRule">
<priority>1</priority> <priority>1</priority>
<example> <example>
<![CDATA[ <![CDATA[
Negative example: Negative example:
//It is hard to tell whether it is number 11 or Long 1. //It is hard to tell whether it is number 11 or Long 1.
Long warn = 1l; Long warn = 1l;
]]> ]]>
</example> </example>
<example> <example>
<![CDATA[ <![CDATA[
Positive example: Positive example:
Long notwarn = 1L; Long notwarn = 1L;
]]> ]]>
</example> </example>
</rule> </rule>
<rule name="UndefineMagicConstantRule" <rule name="UndefineMagicConstantRule"
message="java.constant.UndefineMagicConstantRule.rule.msg" message="java.constant.UndefineMagicConstantRule.rule.msg"
class="com.alibaba.p3c.pmd.lang.java.rule.constant.UndefineMagicConstantRule"> class="com.alibaba.p3c.pmd.lang.java.rule.constant.UndefineMagicConstantRule">
<priority>3</priority> <priority>3</priority>
<example> <example>
<![CDATA[ <![CDATA[
Negative example: Negative example:
//Magic values, except for predefined, are forbidden in coding. //Magic values, except for predefined, are forbidden in coding.
if(key.equals("Id#taobao_1")){ if (key.equals("Id#taobao_1")) {
//... //...
} }
]]> ]]>
</example> </example>
<example> <example>
<![CDATA[ <![CDATA[
Positive example: Positive example:
String KEY_PRE = "Id#taobao_1"; String KEY_PRE = "Id#taobao_1";
if(key.equals(KEY_PRE)){ if (KEY_PRE.equals(key)) {
//... //...
} }
]]> ]]>
</example> </example>
</rule> </rule>
</ruleset> </ruleset>

@ -12,12 +12,12 @@
<example> <example>
<![CDATA[ <![CDATA[
switch( x ){ switch (x) {
case 1 : case 1:
break ; break;
case 2 : case 2:
break ; break;
default : default:
} }
]]> ]]>
</example> </example>
@ -31,8 +31,8 @@
<example> <example>
<![CDATA[ <![CDATA[
if(flag) { if (flag) {
System.out.println("hello world"); System.out.println("hello world");
} }
]]> ]]>
</example> </example>
@ -49,7 +49,7 @@
<![CDATA[ <![CDATA[
Negative example: Negative example:
if ((file.open(fileName, "w") != null) && (...) || (...)) { if ((file.open(fileName, "w") != null) && (...) || (...)) {
... // ...
} }
]]> ]]>
</example> </example>
@ -58,7 +58,7 @@ Negative example:
Positive example: Positive example:
boolean existed = (file.open(fileName, "w") != null) && (...) || (...); boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
if (existed) { if (existed) {
... //...
} }
]]> ]]>
</example> </example>

@ -14,7 +14,7 @@
<![CDATA[ <![CDATA[
public void f(String str){ public void f(String str){
String inner = "hi"; String inner = "hi";
if(inner.equals(str)){ if (inner.equals(str)) {
System.out.println("hello world"); System.out.println("hello world");
} }
} }
@ -34,7 +34,7 @@
Integer a = 235; Integer a = 235;
Integer b = 235; Integer b = 235;
if (a.equals(b)) { if (a.equals(b)) {
//相等 // code
} }
]]> ]]>
</example> </example>
@ -112,7 +112,7 @@
<example> <example>
<![CDATA[ <![CDATA[
反例: Negative example:
String result; String result;
for (String string : tagNameList) { for (String string : tagNameList) {
result = result + string; result = result + string;
@ -121,7 +121,7 @@
</example> </example>
<example> <example>
<![CDATA[ <![CDATA[
正例: Positive example:
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
for (String string : tagNameList) { for (String string : tagNameList) {
stringBuilder.append(string); stringBuilder.append(string);

@ -101,10 +101,9 @@ Negative example:
Iterator<Integer> it=b.iterator(); Iterator<Integer> it=b.iterator();
while(it.hasNext()){ while(it.hasNext()){
Integer temp = it.next(); Integer temp = it.next();
if(delCondition){ if (delCondition) {
it.remove(); it.remove();
} }
} }
]]> ]]>
</example> </example>

@ -1,64 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<test-data> <test-data>
<code-fragment id="constants-ok"><![CDATA[ <code-fragment id="constants-ok"><![CDATA[
public class Foo { public class Foo {
private final static String notWarn = "666l"; private final static String notWarn = "666l";
} }
]]> ]]>
</code-fragment> </code-fragment>
<test-code> <test-code>
<description>UndefineMagicConstant.</description> <description>UndefineMagicConstant.</description>
<expected-problems>0</expected-problems> <expected-problems>0</expected-problems>
<code-ref id="constants-ok" /> <code-ref id="constants-ok"/>
</test-code> </test-code>
<code-fragment id="constants-err"><![CDATA[ <code-fragment id="constants-err"><![CDATA[
public class Foo { public class Foo {
private void method() { private void method() {
Integer i = 1; Integer i = 1;
Integer k = 0; Integer k = 0;
Boolean h = false; Boolean h = false;
Long m = 2L; Long m = 2L;
String n = ""; String n = "";
if(i > 2){ if (i > 2) {
} }
if(i > 1){ if (i > 1) {
} }
if(m > 1L){ if (m > 1L) {
} }
if(i != null){ if (i != null) {
} }
if(h != false){ if (h != false) {
} }
if(n.equals("")){ if (n.equals("")) {
} }
for(int j=0 ; j< 10 ; i++){ for (int j = 0; j < 10; i++) {
if(i > 2){ if (i > 2) {
} }
if(i != null){ if (i != null) {
} }
} }
while(k < 1){ while (k < 1) {
if(i > 2){ if (i > 2) {
} }
k++; k++;
} }
} }
} }
]]> ]]>
</code-fragment> </code-fragment>
<test-code> <test-code>
<description>UndefineMagicConstant.</description> <description>UndefineMagicConstant.</description>
<expected-problems>2</expected-problems> <expected-problems>2</expected-problems>
<expected-linenumbers>8,20</expected-linenumbers> <expected-linenumbers>8,20</expected-linenumbers>
<code-ref id="constants-err" /> <code-ref id="constants-err"/>
</test-code> </test-code>
<code-fragment id="constants-err-2"><![CDATA[ <code-fragment id="constants-err-2"><![CDATA[
public class Foo { public class Foo {
private void method(String path) { private void method(String path) {
if (null == path || !path.startsWith("/home/admin/leveldb/") if (null == path || !path.startsWith("/home/admin/leveldb/")
@ -67,13 +67,13 @@
} }
} }
]]> ]]>
</code-fragment> </code-fragment>
<test-code> <test-code>
<description>UndefineMagicConstant.</description> <description>UndefineMagicConstant.</description>
<expected-problems>1</expected-problems> <expected-problems>1</expected-problems>
<expected-linenumbers>3</expected-linenumbers> <expected-linenumbers>3</expected-linenumbers>
<code-ref id="constants-err-2" /> <code-ref id="constants-err-2"/>
</test-code> </test-code>
</test-data> </test-data>

@ -1,52 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<test-data> <test-data>
<code-fragment id="sets-UnsupportedExceptionWithModifyAsListRule-ok"><![CDATA[ <code-fragment id="sets-UnsupportedExceptionWithModifyAsListRule-ok"><![CDATA[
public class Foo { public class Foo {
private void method(long aLong) { private void method(long aLong) {
List<String> t = Arrays.asList("a","b","c"); List<String> t = Arrays.asList("a","b","c");
}
} }
}
]]> ]]>
</code-fragment> </code-fragment>
<test-code> <test-code>
<description>sets-UnsupportedExceptionWithModifyAsListRule-ok.</description> <description>sets-UnsupportedExceptionWithModifyAsListRule-ok.</description>
<expected-problems>0</expected-problems> <expected-problems>0</expected-problems>
<code-ref id="sets-UnsupportedExceptionWithModifyAsListRule-ok" /> <code-ref id="sets-UnsupportedExceptionWithModifyAsListRule-ok"/>
</test-code> </test-code>
<code-fragment id="sets-UnsupportedExceptionWithModifyAsListRule-warn"><![CDATA[ <code-fragment id="sets-UnsupportedExceptionWithModifyAsListRule-warn"><![CDATA[
public class Foo { public class Foo {
private void method1() { private void method1() {
if(true){ if (true) {
List<String> list = Arrays.asList("a","b","c"); List<String> list = Arrays.asList("a", "b", "c");
list.add("d"); list.add("d");
list.remove("22"); list.remove("22");
list.clear(); list.clear();
} }
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
list.add("b"); list.add("b");
list.remove("b"); list.remove("b");
} }
private void method2() { private void method2() {
if(true){ if (true) {
List<String> list = Arrays.asList("a","b","c"); List<String> list = Arrays.asList("a", "b", "c");
list.add("d"); list.add("d");
} }
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
list.add("b"); list.add("b");
} }
} }
]]> ]]>
</code-fragment> </code-fragment>
<test-code> <test-code>
<description>sets-UnsupportedExceptionWithModifyAsListRule-warn.</description> <description>sets-UnsupportedExceptionWithModifyAsListRule-warn.</description>
<expected-problems>4</expected-problems> <expected-problems>4</expected-problems>
<expected-linenumbers>5,6,7,17</expected-linenumbers> <expected-linenumbers>5,6,7,17</expected-linenumbers>
<code-ref id="sets-UnsupportedExceptionWithModifyAsListRule-warn" /> <code-ref id="sets-UnsupportedExceptionWithModifyAsListRule-warn"/>
</test-code> </test-code>
</test-data> </test-data>
Loading…
Cancel
Save