Collections.emptyList() instead of null check?

后端 未结 9 1084
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-04 02:59

If I have a rarely used collection in some class which may be instantiated many times, I may sometimes resort to the following \"idiom\" in order to save unnecessary object crea

9条回答
  •  情歌与酒
    2021-02-04 03:16

    I find it easiest to follow this convention:

    1. If the point of my methods is to return a Collection, the method never returns null. Null is ambiguous. Instead I return Collection.emptyXXX() or ImmutableXXX.of() if using Guava.

    2. If I have an object which is maintaining an internal list as a member, instantiate it in the constructor. I try not to do lazy instantiation unless I can prove its a significant gain because lazy code, in my opinion, tends to be more difficult to debug when issues arise.

    I really see immutable or unmodifiable empty collections being a part of a contract external to objects. If you are using the collection internally, I can only really see using immutable collections if you have a good reason (concurrency, consistency, immutability of the object)

提交回复
热议问题