Skip to content

Commit 40eaede

Browse files
author
骏烈
committed
code format
alibaba#107
1 parent 1ade912 commit 40eaede

File tree

10 files changed

+253
-253
lines changed

10 files changed

+253
-253
lines changed

eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/CodeAnalysis.kt

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ object CodeAnalysis {
6161
if (monitor.isCanceled) {
6262
return@run Status.CANCEL_STATUS
6363
}
64-
if(it.isAccessible){
64+
if (it.isAccessible) {
6565
it.accept(fileVisitor)
6666
}
6767
}

p3c-pmd/README.md

+83-83
Original file line numberDiff line numberDiff line change
@@ -28,31 +28,31 @@ P3C-PMD implements 49 rules involved in *Alibaba Java Coding Guidelines*, based
2828
* 2 ``[Mandatory]`` A meaningful thread name is helpful to trace the error information, so assign a name when creating threads or thread pools.
2929
Positive example:
3030

31-
```java
32-
public class TimerTaskThread extends Thread {
33-
public TimerTaskThread(){
34-
super.setName("TimerTaskThread"); … }
35-
```
31+
```java
32+
public class TimerTaskThread extends Thread {
33+
public TimerTaskThread(){
34+
super.setName("TimerTaskThread"); … }
35+
```
3636
* 3 ``[Mandatory]`` Threads should be provided by thread pools. Explicitly creating threads is not allowed.
3737
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.
3838
* 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.
3939
Note: Below are the problems created by usage of Executors for thread pool creation:
40-
1. FixedThreadPool and SingleThreadPool:
41-
Maximum request queue size Integer.MAX_VALUE. A large number of requests might cause OOM.
42-
2. CachedThreadPool and ScheduledThreadPool:
43-
The number of threads which are allowed to be created is Integer.MAX_VALUE. Creating too many threads might lead to OOM.
40+
1. FixedThreadPool and SingleThreadPool:
41+
Maximum request queue size Integer.MAX_VALUE. A large number of requests might cause OOM.
42+
2. CachedThreadPool and ScheduledThreadPool:
43+
The number of threads which are allowed to be created is Integer.MAX_VALUE. Creating too many threads might lead to OOM.
4444
* 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.
4545
Positive example: Pay attention to thread-safety when using DateUtils. It is recommended to use below:
4646

47-
```java
48-
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
49-
@Override
50-
protected DateFormat initialValue() {
51-
return new SimpleDateFormat("yyyy-MM-dd");
52-
}
53-
};
54-
```
55-
Note: In JDK8, Instant can be used to replace Date; likewise Calendar is replaced by LocalDateTime, and SimpleDateFormatter is replaced by DateTimeFormatter.
47+
```java
48+
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
49+
@Override
50+
protected DateFormat initialValue() {
51+
return new SimpleDateFormat("yyyy-MM-dd");
52+
}
53+
};
54+
```
55+
Note: In JDK8, Instant can be used to replace Date; likewise Calendar is replaced by LocalDateTime, and SimpleDateFormatter is replaced by DateTimeFormatter.
5656
* 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.
5757
* 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.
5858
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
7070
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.
7171
Positive example:
7272

73-
```java
74-
List<String> list = new ArrayList<String>(2);
75-
list.add("guan");
76-
list.add("bao");
77-
String[] array = new String[list.size()];
78-
array = list.toArray(array);
79-
```
73+
```java
74+
List<String> list = new ArrayList<String>(2);
75+
list.add("guan");
76+
list.add("bao");
77+
String[] array = new String[list.size()];
78+
array = list.toArray(array);
79+
```
8080
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.
8181
* 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.
8282
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.
8383

84-
```java
85-
String[] str = new String[] { "a", "b" };
86-
List<String> list = Arrays.asList(str);
87-
```
84+
```java
85+
String[] str = new String[] { "a", "b" };
86+
List<String> list = Arrays.asList(str);
87+
```
8888
Case 1: list.add("c"); will throw a runtime exception.
8989
Case 2: str[0]= "gujin"; list.get(0) will be modified.
9090
* 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.
9191
Counter example:
9292

93-
```java
94-
List<String> a = new ArrayList<String>();
95-
a.add("1");
96-
a.add("2");
97-
for (String temp : a) {
98-
if ("1".equals(temp)){
99-
a.remove(temp);
100-
}
101-
}
102-
```
103-
Note: If you try to replace "1" with "2", you will get an unexpected result.
93+
```java
94+
List<String> a = new ArrayList<String>();
95+
a.add("1");
96+
a.add("2");
97+
for (String temp : a) {
98+
if ("1".equals(temp)) {
99+
a.remove(temp);
100+
}
101+
}
102+
```
103+
Note: If you try to replace "1" with "2", you will get an unexpected result.
104104
Positive example:
105105

106-
```java
107-
Iterator<String> it = a.iterator();
108-
while (it.hasNext()) {
109-
String temp = it.next();
110-
if (delete condition) {
111-
it.remove();
112-
}
113-
}
114-
```
106+
```java
107+
Iterator<String> it = a.iterator();
108+
while (it.hasNext()) {
109+
String temp = it.next();
110+
if (delete condition) {
111+
it.remove();
112+
}
113+
}
114+
```
115115
* 6``[Recommended]`` Set a size when initializing a collection if possible.
116116
Note: Better to use ArrayList(int initialCapacity) to initialize ArrayList.
117117

@@ -145,9 +145,9 @@ Counter example: boolean isSuccess; The method name will be isSuccess() and then
145145
* 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.
146146
Positive example: com.alibaba.open.util can be used as package name for utils;
147147
* 10 There are mainly two rules for interface and corresponding implementation class naming:
148-
1. ``[Mandatory]`` All Service and DAO classes must be interface based on SOA principle. Implementation class names should be ended with Impl.
148+
1. ``[Mandatory]`` All Service and DAO classes must be interface based on SOA principle. Implementation class names should be ended with Impl.
149149
Positive example: CacheServiceImpl to implement CacheService.
150-
2. ``[Recommended]`` If the interface name is to indicate the ability of the interface, then its name should be adjective.
150+
2. ``[Recommended]`` If the interface name is to indicate the ability of the interface, then its name should be adjective.
151151
Positive example: AbstractTranslator to implement Translatable.
152152

153153
### <font color="green">Constant Conventions</font>
@@ -167,9 +167,9 @@ Note: java.util.Objects#equals (a utility class in JDK7) is recommended.
167167
* 5 ``[Mandatory]`` The wrapper classes should be compared by equals method rather than by symbol of '==' directly.
168168
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.
169169
* 6 ``[Mandatory]`` Rules for using primitive data types and wrapper classes:
170-
1. Members of a POJO class must be wrapper classes.
171-
2. The return value and arguments of a RPC method must be wrapper classes.
172-
3. ``[Recommended]`` Local variables should be primitive data types.
170+
1. Members of a POJO class must be wrapper classes.
171+
2. The return value and arguments of a RPC method must be wrapper classes.
172+
3. ``[Recommended]`` Local variables should be primitive data types.
173173
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.
174174
 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.
175175
 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
178178
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.
179179
* 9 ``[Recommended]`` Use the append method in StringBuilder inside a loop body when concatenating multiple strings.
180180

181-
Counter example:
181+
Counter example:
182182

183-
```java
183+
```java
184184
String str = "start";
185185
for(int i=0; i<100; i++) {
186186
str = str + "hello";
187187
}
188-
```
189-
190-
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.
188+
```
189+
190+
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.
191191

192192
### <font color="green">Flow Control Statements</font>
193193
* 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.
194194
* 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:
195195

196-
```java
197-
if (condition) statements;
198-
```
196+
```java
197+
if (condition) statements;
198+
```
199199
* 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.
200200
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.
201201
Positive example:
202202
203-
```java
204-
// please refer to the pseudo-code as follows
205-
boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
206-
if (existed) {
207-
...
208-
}
209-
```
203+
```java
204+
// please refer to the pseudo-code as follows
205+
boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
206+
if (existed) {
207+
//...
208+
}
209+
```
210210
211-
Counter example:
211+
Counter example:
212212
213-
```java
214-
if ((file.open(fileName, "w") != null) && (...) || (...)) {
215-
...
216-
}
217-
```
213+
```java
214+
if ((file.open(fileName, "w") != null) && (...) || (...)) {
215+
// ...
216+
}
217+
```
218218
219219
### <font color="green">Exception</font>
220220
* 4 ``[Mandatory]`` Make sure to invoke the rollback if a method throws an Exception. Rollbacks are based on the context of the coding logic.
221221
* 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.
222222
* 6 ``[Recommended]`` One of the most common errors is NullPointerException. Pay attention to the following situations:
223-
* 1 If the return type is primitive, return a value of wrapper class may cause NullPointerException.
224-
  Counter example: public int f() { return Integer } Unboxing a null value will throw a NullPointerException.
225-
* 2 The return value of a database query might be null.
226-
* 3 Elements in collection may be null, even though Collection.isEmpty() returns false.
227-
* 4 Return values from an RPC might be null.
228-
* 5 Data stored in sessions might by null.
229-
* 6 Method chaining, like obj.getA().getB().getC(), is likely to cause NullPointerException.
230-
  Positive example: Use Optional to avoid null check and NPE (Java 8+).
223+
* 1 If the return type is primitive, return a value of wrapper class may cause NullPointerException.
224+
  Counter example: public int f() { return Integer } Unboxing a null value will throw a NullPointerException.
225+
* 2 The return value of a database query might be null.
226+
* 3 Elements in collection may be null, even though Collection.isEmpty() returns false.
227+
* 4 Return values from an RPC might be null.
228+
* 5 Data stored in sessions might by null.
229+
* 6 Method chaining, like obj.getA().getB().getC(), is likely to cause NullPointerException.
230+
  Positive example: Use Optional to avoid null check and NPE (Java 8+).
231231
232232
### <font color="green">Code Comments</font>
233233
* 1 ``[Mandatory]`` Javadoc should be used for classes, class variables and methods. The format should be '/** comment **/', rather than '// xxx'.

p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/util/NodeUtils.java

+12-11
Original file line numberDiff line numberDiff line change
@@ -25,34 +25,35 @@
2525
* @date 2016/11/16
2626
*/
2727
public class NodeUtils {
28-
public static boolean isParentOrSelf(Node descendant,Node ancestor){
29-
if(descendant == ancestor) {
28+
public static boolean isParentOrSelf(Node descendant, Node ancestor) {
29+
if (descendant == ancestor) {
3030
return true;
3131
}
32-
if(descendant == null || ancestor == null){
32+
if (descendant == null || ancestor == null) {
3333
return false;
3434
}
3535
Node parent = descendant.jjtGetParent();
36-
while(parent != ancestor && parent != null){
36+
while (parent != ancestor && parent != null) {
3737
parent = parent.jjtGetParent();
3838
}
3939
return parent == ancestor;
4040
}
4141

4242
/**
4343
* TODO optimize
44+
*
4445
* @param expression expression
4546
* @return true if wrapper type
4647
*/
4748
public static boolean isWrapperType(ASTPrimaryExpression expression) {
4849
return TypeHelper.isA(expression, Integer.class)
49-
|| TypeHelper.isA(expression, Long.class)
50-
|| TypeHelper.isA(expression, Boolean.class)
51-
|| TypeHelper.isA(expression, Byte.class)
52-
|| TypeHelper.isA(expression, Double.class)
53-
|| TypeHelper.isA(expression, Short.class)
54-
|| TypeHelper.isA(expression, Float.class)
55-
|| TypeHelper.isA(expression, Character.class);
50+
|| TypeHelper.isA(expression, Long.class)
51+
|| TypeHelper.isA(expression, Boolean.class)
52+
|| TypeHelper.isA(expression, Byte.class)
53+
|| TypeHelper.isA(expression, Double.class)
54+
|| TypeHelper.isA(expression, Short.class)
55+
|| TypeHelper.isA(expression, Float.class)
56+
|| TypeHelper.isA(expression, Character.class);
5657
}
5758

5859
public static boolean isConstant(ASTFieldDeclaration field) {

p3c-pmd/src/main/resources/rulesets/java/ali-concurrent.xml

+7-7
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ Positive example 2:
2727
2828
//Common Thread Pool
2929
ExecutorService pool = new ThreadPoolExecutor(5, 200,
30-
0L, TimeUnit.MILLISECONDS,
31-
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
30+
0L, TimeUnit.MILLISECONDS,
31+
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
3232
3333
pool.execute(()-> System.out.println(Thread.currentThread().getName()));
3434
pool.shutdown();//gracefully shutdown
@@ -63,7 +63,7 @@ Positive example 3:
6363
<![CDATA[
6464
//org.apache.commons.lang3.concurrent.BasicThreadFactory
6565
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
66-
new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
66+
new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
6767
executorService.scheduleAtFixedRate(new Runnable() {
6868
@Override
6969
public void run() {
@@ -84,9 +84,9 @@ Positive example 3:
8484
<example>
8585
<![CDATA[
8686
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
87-
.setNameFormat("demo-pool-%d").build();
87+
.setNameFormat("demo-pool-%d").build();
8888
ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
89-
0L, TimeUnit.MILLISECONDS,
89+
0L, TimeUnit.MILLISECONDS,
9090
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
9191
9292
singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName()));
@@ -104,9 +104,9 @@ Positive example 3:
104104
<example>
105105
<![CDATA[
106106
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
107-
.setNameFormat("demo-pool-%d").build();
107+
.setNameFormat("demo-pool-%d").build();
108108
ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
109-
0L, TimeUnit.MILLISECONDS,
109+
0L, TimeUnit.MILLISECONDS,
110110
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
111111
112112
singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName()));

0 commit comments

Comments
 (0)