异常情况,返回长度为0的容器好过返回null。
- 返回长度为0的容器,后续代码使用容器前,无需判断是否为空。
- 代码更优美
- 避免很多平时不出现,但是可能会出现的NullPointException.
- 不用去时刻记得检查容器是否为空。
- 避免了很多ForceClose。一些错误的场景很难复现。
public static List<String> getItems1() { if (new Random().nextInt(10) > 5) {// 异常情况,返回null return null; } List<String> list = new ArrayList<String>(); for (int i = 0; i < 5; i++) { list.add("item1 + " + i); } return list; }
List<String> list = getItems1(); if (list != null) {// 讨厌的判断,如果后续有用到,需要这种判断。 for (String s : list) { System.out.println(s); } }
修改后
public static List<String> getItems2() { if (new Random().nextInt(10) > 5) {// 异常情况,返回长度为0的容器 return Collections.emptyList(); } List<String> list = new ArrayList<String>(); for (int i = 0; i < 5; i++) { list.add("item2 - " + i); } return list; }
for (String s : getItems2()) {// 更通用,无需特别使用一些判断 System.out.println(s); }