The PMD source code analyzer allows to write rules as XPath expressions.
I'm working at cleaning up an Apex codebase where I find frequently the following mistake: !someCollection.isEmpty() && someCollection != null
.
The correct approach would be to check for null first: someCollection != null && !someCollection.isEmpty()
.
Using my trusted editor I can use a RegEx to find these items: && [a-zA-Z0-9]* != null
. Works like a charm. Now I try to create a custom PMD rule for it, but my XPath regex doesn't return any value in the PMD Designer:
<rule message="Apex code must check != null before .isEmpty()" name="NullValueCheckBeforeEmptyCheck" class="net.sourceforge.pmd.lang.rule.XPathRule">
<description>Apex code must check != null before .isEmpty()</description>
<priority>1</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//*[matches(@Image,'&& [a-zA-Z0-9]* != null')]
]]>
</value>
</property>
</properties>
</rule>
I tried to initial check //*[matches(@Image,'if')]
but even that returned no result.
What do I miss?
Sample Apex that should trigger the rule:
global class caseShareBatch {
global void execute(List<Case> caseShareList){
if(!caseShareList.isEmpty() && caseShareList != null) {
insert caseShareList;
}
}
}