Tuesday 10 May 2016

Empty arrays and collections should be returned instead of null

Returning null instead of an actual array or collection forces callers of the method to explicitly test for nullity, making them more complex and less readable. Moreover, in many cases, null is used as a synonym for empty.

public static Result[] getResults() {
  return null;                             // Non-Compliant
}

public static void main(String[] args) {
  Result[] results = getResults();

  if (results != null) {                   // Nullity test required to prevent NPE
    for (Result result: results) {
      /* ... */
    }
  }
}

should be refactored into:

public static Result[] getResults() {
  return new Result[0];                    // Compliant
}

public static void main(String[] args) {
  for (Result result: getResults()) {
    /* ... */
  }
}

This rule also applies to collections:

public static List<Result> getResults() {
  return null;                             // Non-Compliant
}

should be refactored into:

public static List<Result> getResults() {
  return Collections.EMPTY_LIST;           // Compliant
}

Return an empty collection instead of null.


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...