Java False positive "Return an empty array instead of null" - edge case

299 views
Skip to first unread message

t...@berrycloud.co.uk

unread,
Mar 14, 2017, 1:45:37 PM3/14/17
to SonarQube
Hi

The following is from a class that extends HttpServletRequestWrapper. HttpServletRequestWrapper extends HttpServletRequest which in turn implements ServletRequest. The documentation for the method getParameterValues in the interface ServletRequest specifically states that the method should return null if the parameter can not be found.

However Sonar says that this is a code smell.  If I am implementing or overriding a third party method what choice do I have to avoid the code smell?

I hesitate to post this since I don't believe there is much that can be done but I will be grateful for any suggestions.

    @Override
    public String[] getParameterValues(final String name) {
 
        final List<String> parametersList = parameters.get(name);
 
        if (parametersList == null) {
            return null;
Return an empty array instead of null.  
  •  
  • L202
  •  
  •  
  • Code Smell
  •  
  •  Major
  •  
  •  
  •  
  • 30min effort
  •  
        }
 
        return parametersList.stream().toArray(String[]::new);
 
    }
 

Freddy Mallet

unread,
Mar 15, 2017, 4:28:34 PM3/15/17
to SonarQube, t...@berrycloud.co.uk
Hi Tom,

Thanks for reporting what you're correctly considering as an irrelevant issue in this particular context.

The purpose of this rule is to reinforce a safer coding practice that must lead to prevent facing some unexpected NullPointerException later. In a perfect world, this rule should be indeed smart enough to guess that this coding practice is irrelevant here due to the contract of the overridden method. But as you said, getting this knowledge seems ultimately hard.

But anyway, even if we're a bit stuck here, feel free to keep on reporting such kind of irrelevant issues.
Freddy
Reply all
Reply to author
Forward
0 new messages