my files互联网科技 技术栈

《阿里巴巴Java规约插件》使用总结

2017-10-16  本文已影响145人  黄油伯伯
前言

小编用自己的项目做白老鼠,试试这个阿里巴巴荣誉出品的《Java规约插件》


结果居然有4800+条问题!!简直吓得小编怀疑人生有木有!?(默哀0.01秒)小编依旧怀着认真的科学精神进入试验田(快开车,别废话!)。如想了解如何安装插件和插件的使用技巧请猛戳:http://www.jianshu.com/p/834899aa90b4
入题

扫描出三个分类结果(类jira的bug优先级分为:blocker,critical,major,minor,trivial)

具体的语法问题,值得学习下:

Blocker 有妨碍的

Positive example 1:
//org.apache.commons.lang3.concurrent.BasicThreadFactory
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());

Positive example 2:
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("demo-pool-%d").build();

//Common Thread Pool
ExecutorService pool = new ThreadPoolExecutor(5, 200,
     0L, TimeUnit.MILLISECONDS,
     new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

pool.execute(()-> System.out.println(Thread.currentThread().getName()));
pool.shutdown();//gracefully shutdown

Positive example 3:
<bean id="userThreadPool"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="10" />
<property name="maxPoolSize" value="100" />
<property name="queueCapacity" value="2000" />

<property name="threadFactory" value= threadFactory />
    <property name="rejectedExecutionHandler">
        <ref local="rejectedExecutionHandler" />
    </property>
</bean>
//in code
userThreadPool.execute(thread);

Object的equals方法容易抛空指针异常,应使用常量或确定有值的对象来调用equals。

public void f(String str){
    String inner = "hi";
    if(inner.equals(str)){
        System.out.println("hello world");
    }
}

Positive example 1:
private static final String FORMAT = "yyyy-MM-dd HH:mm:ss";
public String getFormat(Date date){
SimpleDateFormat dateFormat = new SimpleDateFormat(FORMAT);
return sdf.format(date);
}

Positive example 2:
private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void getFormat(){
synchronized (sdf){
sdf.format(new Date());
….;
}

Positive example 3:
private static final ThreadLocal<DateFormat> DATE_FORMATTER = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};

Negative example:
if ((file.open(fileName, "w") != null) && (...) || (...)) {
...
}

Positive example:
boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
if (existed) {
...
}

Negative example:
Map<String, String> map = new HashMap<String, String>();

Positive example:
Map<String, String> map = new HashMap<String, String>(16);

小结

总的来说,阿里巴巴Java规约插件还是对项目很有帮助的,大家用起来吧。

上一篇下一篇

猜你喜欢

热点阅读