当前位置: 移动技术网 > IT编程>开发语言>Java > 28个Java开发常用规范技巧总结

28个Java开发常用规范技巧总结

2019年07月02日  | 移动技术网IT编程  | 我要评论

1、类的命名使用驼峰式命名的规范。

例如:userservice,但是以下情景例外:do / bo / po / dto / vo。

例如说:userpo,studentpo(po,vo,dto,等这类名词需要全大写)

@data
@builder
public class custombodydto {

    private string name;

    private string idcode;

    private string status;
}

 

2、如果在模块或者接口,类,方法中使用了设计模式,那么请在命名的时候体现出来。

例如说:tokenfactory,loginproxy等。

public class tokenfactory {


    public tokendto buildtoken(logininfo logininfo) {
        string token = uuid.randomuuid().tostring();
        tokendto tokendto = tokendto.builder()
                .token(token)
                .createtime(localdatetime.now())
                .build();
        string rediskey = rediskeybuilder.buildtokenkey(token);
        redisservice.setobject(rediskey, logininfo, timeout.one_day * 30 * 2);
        log.info("创建token成功|logininfo={}", logininfo.tostring());
        return tokendto;
    }
}

 

3、object 的 equals 方法容易抛空指针异常。

从源码来进行分析equals方法是属于object类的,如果调用方为null,那么自然在运行的时候会抛出空指针异常的情况。

object类中的源码:

    public boolean equals(object obj) {
        return (this == obj);
    }

 

为了避免这种现况出现,在比对的时候尽量将常量或者有确定值的对象置前。

例如说:

正确:“test”.equals(object);
错误:object.equals(“test”);

 

4、对于所有相同类型的包装类进行比较的时候,都是用equal来进行操作。

对于integer类来说,当相应的变量数值范围在-128到127之间的时候,该对象会被存储在integercache.cache里面,因此会有对象复用的情况发生。

所以对于包装类进行比较的时候,最好统一使用equal方法。

    private static class integercache {
        static final int low = -128;
        static final int high;
        static final integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            string integercachehighpropvalue =
                sun.misc.vm.getsavedproperty("java.lang.integer.integercache.high");
            if (integercachehighpropvalue != null) {
                try {
                    int i = parseint(integercachehighpropvalue);
                    i = math.max(i, 127);
                    // maximum array size is integer.max_value
                    h = math.min(i, integer.max_value - (-low) -1);
                } catch( numberformatexception nfe) {
                    // if the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new integer(j++);

            // range [-128, 127] must be interned (jls7 5.1.7)
            assert integercache.high >= 127;
        }

        private integercache() {}
    }

  public static integer valueof(int i) {
        if (i >= integercache.low && i <= integercache.high)
            return integercache.cache[i + (-integercache.low)];
        return new integer(i);
    }

 

5、所有的pojo类中的属性最好统一使用包装类属性类型数据。rpc方法的返回值和参数都统一使用包装类数据。局部变量中使用基本的数据类型。

对于实际的应用场景来说,例如说一个学生类,当我们设置里面的成绩字段为int类型的时候,如果学生没有考试,那么这个成绩字段应该为空,但是int默认会赋值为0,那么这个时候使用基本数据类型就容易产生误区,到底是考了0分,还是说没有参加考试。

如果换成使用包装类integer类型的话,就可以通过null值来进行区分了。

6、当pojo类在进行编写的时候要重写相应的tostring方法,如果该pojo中继承了另外的一个pojo类,那么请在相应的tostring函数中加入super.tostring()方法。

通过重写tostring方法有利于在日志输出的时候查看相应对象的属性内容进行逐一分析,对于一些有继承关系的对象而言,加入了super.tostring方法更加有助于对该对象的理解和分析。

7、在pojo的getter和setter方法里面,不要增加业务逻辑的代码编写,这样会增加问题排查的难度。

正确做法:

public class user {
    private integer id;

    private string username;

    public integer getid() {
        return id;
    }

    public user setid(integer id) {
        this.id = id;
        return this;
    }

    public string getusername() {
        return username;
    }

    public user setusername(string username) {
        this.username = username;
        return this;
    }
}

 

错误做法:

public class user {
    private integer id;

    private string username;

    public integer getid() {
        return id;
    }

    public user setid(integer id) {
        this.id = id;
        return this;
    }

    public string getusername() {
        return "key-prefix-"+username;
    }

    public user setusername(string username) {
        this.username = "key-prefix-"+username;
        return this;
    }
}

 

8、final 可以声明类、成员变量、方法、以及本地变量。

下列情况使用 final 关键字:

  • 不允许被继承的类,如:string 类。

  • 不允许修改引用的域对象,如:pojo 类的域变量。

  • 不允许被重写的方法,如:pojo 类的 setter 方法。

  • 不允许运行过程中重新赋值的局部变量。

  • 避免上下文重复使用一个变量,使用 final 描述可以强制重新定义一个变量,方便更好地进行重构。

9、对于任何类而言,只要重写了equals就必须重写hashcode。

举例说明:

1)hashset在存储数据的时候是存储不重复对象的,这些对象在进行判断的时候需要依赖hashcode和equals方法,因此需要重写。

2)在自定义对象作为key键时,需要重写hashcode和equals方法,例如说string类就比较适合用于做key来使用。

10、不要在 foreach 循环里进行元素的 remove/add 操作。

remove 元素请使用 iterator方式,如果并发操作,需要对 iterator 对象加锁。

iterator<string> iterator = list.iterator();
while (iterator.hasnext()) {
string item = iterator.next();
if (删除元素的条件) {
iterator.remove();
}
}

 

11、使用hashmap的时候,可以指定集合的初始化大小。

例如说,hashmap里面需要存放10000个元素,但是由于没有进行初始化大小操作,所以在添加元素的时候,hashmap的内部会一直在进行扩容操作,影响性能。

那么为了减少扩容操作,可以在初始化的时候将hashmap的大小设置为:已知需要存储的大小/负载因子(0.75)+1

hashmap hashmap=new hashmap<>(13334);

 

12、map类集合中,k/v对于null类型存储的情况:

集合名称keyvalue说明
hashmap 允许为null 允许为null 线程不安全
treemap 不允许为null 允许为null 线程不安全
hashtable 不允许为null 不允许为null 线程安全
concurrenthashmap 不允许为null 不允许为null 线程安全

13、可以利用 set 元素唯一的特性,可以快速对一个集合进行去重操作,避免使用 list 的contains 方法进行遍历、对比、去重操作。

通关观察可以发现,hashset底层通过将传入的值再传入到一个hashmap里面去进行操作,进入到hashmap里面之后,会先通过调用该对象的hashcode来判断是否有重复的值,如果有再进行equals判断,如果没有相同元素则插入处理。

   public boolean add(e e) {
        return map.put(e, present)==null;
    }

 

14、线程池不允许使用 executors 去创建,而是通过 threadpoolexecutor 的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。

错误做法:

executorservice executors = executors.newsinglethreadexecutor();
scheduledexecutorservice scheduledexecutorservice = executors.newscheduledthreadpool(5);

 

对于线程池的参数需要有深入的理解后,结合实际的机器参数来进行参数设置,从而防止在使用中出现异常。

    executorservice fixedexecutorservice = new threadpoolexecutor(
                1,
                2, 
                60,
                timeunit.seconds,
                 linkedblockingqueue, 
                new mythreadfactory(),
                new threadpoolexecutor.abortpolicy()
        );

 

ps:使用executors.new方式创建线程池的缺点:

对于fixedthreadpool 和 singlethreadpool而言

允许的请求队列长度为 integer.max_value,可能会堆积大量的请求,从而导致 oom。

对于cachedthreadpool 和 scheduledthreadpool而言

允许的创建线程数量为 integer.max_value,可能会创建大量的线程,从而导致 oom。

15、使用一些日期类的时候,推荐使用localdatetime来替代calendar类,或者说使用instant来替代掉date类。

16、尽量避免在for循环里面执行try-catch操作,可以选择将try-catch操作放在循环体外部使用。

 正确做法:

try {
         for (int i = 0; i < 100; i++) {
             dosomething();
          }
       }catch (exception e){
            e.printstacktrace();
       }

 

不推荐做法:

for (int i = 0; i < 100; i++) {

      try {
                dosomething();
            } catch (exception e) {
                e.printstacktrace();
            }
        }

 

17、对于大段的代码进行try-catch操作,这是一种不负责任的行为,将稳定的代码也都包围在了try-catch语句块里面没能很好的分清代码的稳定性范围。

通常我们称在运行中不会出错的代码块为稳定性代码,可能会有异常出错的部分为非稳定性代码块,后者才是try-catch重点需要关注的对象。

18、在jdk7之后,对于流这类需要关闭连接释放资源的对象,可以使用try-with-resource处理机制来应对。

例如下方代码:

  file file = new file("*****");
        try (fileinputstream fin = new fileinputstream(file)) {
            //执行相关操作
        } catch (exception e) {
            //异常捕获操作
        }

 

19、使用arraylist的时候,如果清楚它的指定大小的话,可以尽量在初始化的时候进行大小指定,因为随着arraylist不断添加新的元素之后,链表的体积会不断增大扩容。

    private void grow(int mincapacity) {
        // overflow-conscious code
        int oldcapacity = elementdata.length;
        int newcapacity = oldcapacity + (oldcapacity >> 1);
        if (newcapacity - mincapacity < 0)
            newcapacity = mincapacity;
        if (newcapacity - max_array_size > 0)
            newcapacity = hugecapacity(mincapacity);
        // mincapacity is usually close to size, so this is a win:
        elementdata = arrays.copyof(elementdata, newcapacity);
    }

 

20、对于一些短信,邮件,电话,下单,支付等应用场景而言,开发的时候需要设置相关的防重复功能限制,防止出现某些恶意刷单,滥刷这类型情况。

21、对于敏感词汇发表的时候,需要考虑一些文本过滤的策略。

这一块的功能可以考虑直接接入市面上已有的成熟的ugc监控服务,或者使用公司内部自研的ugc过滤工具,防止用户发表恶意评论等情况出现。

22、在建立索引的时候,对于索引的命名需要遵循一定的规范:

索引类型命名规则案例
主键索引 pk_字段名,pk是指primary key pk_order_id
唯一索引 uk_字段名,uk是指 unique key uk_order_id
普通索引 idx_字段名,idx是指 index idx_order_id

23、当我们需要存储一段文本信息的时候,需要先考虑存储文本的长度。

如果文本的长度超过了5000,则不建议再选择使用varchar类型来进行存储,可以考虑使用text类型进行数据存储,这个时候可以考虑单独用一张表来进行存储数据,并且通过一个额外的主键id来对应,从而避免影响其他字段的查询。

24、在进行数据库命名的时候尽量保证数据库的名称和项目工程的名称一致。

25、在进行表结构设计的时候,只要具有唯一性质的字段都需要建立唯一索引。

这样有助于后期进行查询的时候提高查询的效率,没有唯一索引这一层的保障,即使在业务层加入了拦截,但是依然容易造成线上脏数据的产生。

26、在进行order by这类型sql查询的时候,需要注意查询索引的有序性。

关于索引的建立,可以去了解一下索引的星级评定,例如三星索引。但是个人认为索引没有所谓的最优性,需要结合实际的业务场景来设计。

27、在mysql中,使用count(*)会统计值为 null 的行,而 count(列名)不会统计此列为 null 值的行。

28、在进行数据库存储引擎选择的时候,需要结合相关的应用场景来选择,如果是需要应用在select操作较多的情况下,可以选择使用myisam存储引擎,如果是对于数据的insert,update,这类修改操作较多的业务场景,则优先推荐使用innodb存储引擎。目前普遍互联网公司都推荐使用innodb较多。

 

参考

阿里巴巴java开发手册

 

内容聚合阅

1. 

2. 

3. 

4. 

5. 

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网