org.sonar.l10n.java.rules.squid.S1168.html Maven / Gradle / Ivy
The newest version!
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.
The following code:
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.emptyList(); // Compliant
}
See
- CERT, MSC19-C - For functions that return an array, prefer returning an empty array over a null value
© 2015 - 2025 Weber Informatics LLC | Privacy Policy