GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [java] Fix #6744: ReturnEmptyCollectionRatherThanNull: Analyze possible null return values by fudianchn · Pull Request #6941 · pmd/pmd

[java] Fix #6744: ReturnEmptyCollectionRatherThanNull: Analyze possible null return values #6941

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
UncleOwen merged 3 commits into pmd:main from fudianchn:fix/returnemptycollection-ternary-null-6744
Aug 18, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

[java] Fix #6744: ReturnEmptyCollectionRatherThanNull: Analyze possible null return values #6941

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
3 commits
Select commit Hold shift + click to select a range
fc96f9a
[java] Fix #6744: Analyze possible null return values
fudianchn Aug 5, 2026
92dc1a9
some minor fixes
UncleOwen Aug 18, 2026
44af6d9
Merge branch 'main' into fork/fudianchn/fix/returnemptycollection-ter…
UncleOwen Aug 18, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

3 changes: 3 additions & 0 deletions 3 docs/pages/release_notes.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,13 @@ Note: Type data is not yet accessible in XPath rules or the PMD Rule Designer. T
* [#6270](https://github.com/pmd/pmd/issues/6270): \[java] CommentSize: Skip file header comments.
* java-errorprone
* [#2840](https://github.com/pmd/pmd/issues/2840): \[java] CloseResource: False positive on mocks
* [#3880](https://github.com/pmd/pmd/issues/3880): \[java] ReturnEmptyCollectionRatherThanNull: False negative when a null value is assigned to a local that is later returned
* [#4623](https://github.com/pmd/pmd/issues/4623): \[java] CloseResource: False positive with resource being closed in method
* [#6435](https://github.com/pmd/pmd/issues/6435): \[java] UnconditionalIfStatement: False negative for negated boolean constant
* [#6547](https://github.com/pmd/pmd/issues/6547): \[java] NonSerializableClass: Report non-serializable generic element/value types of collections and maps
* [#6695](https://github.com/pmd/pmd/issues/6695): \[java] ReturnEmptyCollectionRatherThanNull: False negative when null is returned through a local variable
* [#6742](https://github.com/pmd/pmd/issues/6742): \[java] CloseResource: False positive when a correctly-closed resource is declared without initializer
* [#6744](https://github.com/pmd/pmd/issues/6744): \[java] ReturnEmptyCollectionRatherThanNull: False negatives when a returned expression can evaluate to null
* [#6826](https://github.com/pmd/pmd/issues/6826): \[java] AssertEqualsArgumentOrder: False positive for double assertEquals
* [#6900](https://github.com/pmd/pmd/issues/6900): \[java] DoubleCheckedLocking: False negative when the outer null check is written as !(x != null)
* java-multithreading
Expand Down
4 changes: 4 additions & 0 deletions 4 pmd-java/pmd-java-exclude-pmd.properties
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# The @SuppressWarnings for ReturnEmptyCollectionRatherThanNull in NonSerializableClassRule
# is only necessary once 7.27.0 analyzes this code. The pmd-main check uses the released PMD,
# for which it is an UnnecessaryWarningSuppression. Remove this after the 7.27.0 release, see #6941
net.sourceforge.pmd.lang.java.rule.errorprone.NonSerializableClassRule=UnnecessaryWarningSuppression
5 changes: 4 additions & 1 deletion 5 ...src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/NonSerializableClassRule.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
import java.util.Set;
import java.util.stream.Collectors;

import org.checkerframework.checker.nullness.qual.Nullable;

import net.sourceforge.pmd.lang.java.ast.ASTBodyDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTClassDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration;
Expand Down Expand Up @@ -214,7 +216,8 @@ private boolean hasNonSerializableElementType(JTypeMirror typeMirror) {
return false;
}

private Set<String> determinePersistentFields(ASTTypeDeclaration typeDeclaration) {
@SuppressWarnings("PMD.ReturnEmptyCollectionRatherThanNull") // null means no serialPersistentFields declaration
private @Nullable Set<String> determinePersistentFields(ASTTypeDeclaration typeDeclaration) {
if (cachedPersistentFieldNames.containsKey(typeDeclaration)) {
return cachedPersistentFieldNames.get(typeDeclaration);
}
Expand Down
133 changes: 133 additions & 0 deletions 133 ...et/sourceforge/pmd/lang/java/rule/errorprone/ReturnEmptyCollectionRatherThanNullRule.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/

package net.sourceforge.pmd.lang.java.rule.errorprone;

import java.util.Collection;
import java.util.Map;

import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression;
import net.sourceforge.pmd.lang.java.ast.ASTCastExpression;
import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTNullLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression;
import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess;
import net.sourceforge.pmd.lang.java.ast.ReturnScopeNode;
import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule;
import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass;
import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass.AssignmentEntry;
import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass.DataflowResult;
import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass.ReachingDefinitionSet;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.TypeTestUtil;

/**
* For methods that return an array, a {@link Collection} or a {@link Map}, this rule reports
* a {@code return} statement when the value it produces has an explicit {@code null} source.
*
* <p>The analysis is conservative about values it cannot trace: method calls, field reads and
* parameters are not treated as {@code null} without an explicit {@code null} source, and the
* {@code null} literal is ignored when it appears only in a condition, a switch selector or an array
* element rather than in the produced value.
*
* @since 6.37.0 (as XPath) / 7.27.0 (as Java)
*/
public class ReturnEmptyCollectionRatherThanNullRule extends AbstractJavaRulechainRule {
Comment thread
UncleOwen marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.


public ReturnEmptyCollectionRatherThanNullRule() {
super(ASTReturnStatement.class);
}

@Override
public Object visit(ASTReturnStatement returnStmt, Object data) {
ReturnScopeNode target = JavaAstUtils.getReturnTarget(returnStmt);
if (!(target instanceof ASTMethodDeclaration)) {
return data;
}

ASTMethodDeclaration method = (ASTMethodDeclaration) target;
if (!returnsArrayOrCollection(method)) {
return data;
}

ASTExpression expression = returnStmt.getExpr();
if (expression == null) {
return data;
}

if (mayReturnExplicitNull(expression) || reachesExplicitNullThroughLocal(expression)) {
asCtx(data).addViolation(returnStmt);
}
return data;
}

private static boolean returnsArrayOrCollection(ASTMethodDeclaration method) {
JTypeMirror returnType = method.getResultTypeNode().getTypeMirror();
return returnType.isArray()
|| TypeTestUtil.isA(Collection.class, returnType)
|| TypeTestUtil.isA(Map.class, returnType);
}

/**
* Returns true when {@code expression} can produce the value {@code null} through an explicit
* null source. The condition of a conditional and the selector of a switch are value-selecting
* expressions, not produced values, so they are not examined. Local variables are not traced
* here; {@link #reachesExplicitNullThroughLocal(ASTExpression)} handles a bare returned local.
*/
private static boolean mayReturnExplicitNull(ASTExpression expression) {
if (expression instanceof ASTNullLiteral) {
return true;
} else if (expression instanceof ASTConditionalExpression) {
ASTConditionalExpression conditional = (ASTConditionalExpression) expression;
return mayReturnExplicitNull(conditional.getThenBranch())
|| mayReturnExplicitNull(conditional.getElseBranch());
} else if (expression instanceof ASTCastExpression) {
return mayReturnExplicitNull(((ASTCastExpression) expression).getOperand());
} else if (expression instanceof ASTSwitchExpression) {
for (ASTExpression yielded : ((ASTSwitchExpression) expression).getYieldExpressions()) {
if (mayReturnExplicitNull(yielded)) {
return true;
}
}
return false;
} else if (expression instanceof ASTAssignmentExpression) {
ASTAssignmentExpression assignment = (ASTAssignmentExpression) expression;
// Only a plain assignment can carry an explicit null reference as its value;
// compound assignments are not a direct null source.
return !assignment.isCompound()
&& mayReturnExplicitNull(assignment.getRightOperand());
}
return false;
}

/**
* For a bare {@code return localVar;}, follows the reaching definitions of the local variable
* and returns true when any of them has an explicit {@code null} source. This is only applied
* to a variable returned directly, never to one nested in a conditional or switch branch, so a
* null guard around the value is not reinterpreted. Reaching definitions that the dataflow
* analysis cannot fully determine are treated as non-null.
*/
private static boolean reachesExplicitNullThroughLocal(ASTExpression expression) {
if (!JavaAstUtils.isReferenceToLocal(expression)) {
return false;
}
ASTVariableAccess access = (ASTVariableAccess) expression;
DataflowResult dataflow = DataflowPass.getDataflowResult(access.getRoot());
ReachingDefinitionSet reaching = dataflow.getReachingDefinitions(access);
if (reaching.isNotFullyKnown()) {
return false;
}
for (AssignmentEntry def : reaching.getReaching()) {
ASTExpression rhs = def.getRhsAsExpression();
if (rhs != null && mayReturnExplicitNull(rhs)) {
return true;
}
}
return false;
}
}
17 changes: 1 addition & 16 deletions 17 pmd-java/src/main/resources/category/java/errorprone.xml
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2910,7 +2910,7 @@ public class Foo {
<rule name="ReturnEmptyCollectionRatherThanNull"
language="java"
since="6.37.0"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
class="net.sourceforge.pmd.lang.java.rule.errorprone.ReturnEmptyCollectionRatherThanNullRule"
message="Return an empty collection rather than 'null'."
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#returnemptycollectionratherthannull">
<description>
Expand All @@ -2921,21 +2921,6 @@ inadvertent NullPointerExceptions.
See Effective Java, 3rd Edition, Item 54: Return empty collections or arrays instead of null
</description>
<priority>1</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ReturnStatement/NullLiteral
[ancestor::MethodDeclaration[1]
[ArrayType
or ClassType[pmd-java:typeIs('java.util.Collection')
or pmd-java:typeIs('java.util.Map')]]
]
[not(./ancestor::LambdaExpression)]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Example {
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.