[pmd-devel] Custom Apex rule questions
A source code analyzer
Brought to you by:
adangel,
juansotuyo
|
From: Caleb K. <cal...@en...> - 2017-07-13 22:09:55
|
Hi there folks,
I am trying to implement a few more rules for the project I've emailed
about before, before we send it off to our customers. This is working with
Salesforce/Apex classes.
Here they are:
*ApexOptimizeSoqlRule*
Example:
List<Account> acct = […];
for (Account a : acct ) {
}
// add violation
-------------------------------------------
// optimized version
for (Account acct : [Select … ] ) {
}
// all good
For this rule, I was planning on looking at ASTForEachStatement nodes,
checking the children for an ASTSoqlExpression node, as well as looking at
ASTSoqlExpression nodes and checking their parents for a List<>
declaration. However, what I have is not working, so I am wondering if my
basic way of thinking about this rule is wrong, and if I should do
something else.
*ApexSingleSoqlResultRule*
Example:
Account acct = [Select Id From Account Where Name = ‘abc’ ];
// Get QueryException back if 0 or duplicate
// People try to avoid by doing:
List<Account> acct = [Select … LIMIT 1]; // bad practice to avoid dupes etc
--> add violation
if (acct.size() > 0 )
[...]
--------------------------------------------
// Best practice is:
try {
Account acct = […];
} catch (QueryException q){
}
For this rule, I am checking ASTSoqlExpression nodes. If their parent nodes
include a try/catch, no violation. Else, add violation.
I also check the ASTSoqlExpression for a LIMIT 1 since that's how people
avoid the QueryException. But, I don't quite know how to do that.
Maybe something like this?
if(node.getNode().getQuery().toLowerCase().contains("list") &&
node.getNode().getQuery().toLowerCase().contains("limit 1"))
*ApexCommentRule*
The last two rules are related to readability. The first one looks at the
following:
- No class or method comments => add to violation count
For this, can I just use a Java rule, like CommentRequiredRule?
*ApexReadabilityRule*
The last one follows these criteria:
- Lines of code in a method exceed 50 => add to violation count
- Nested if statements exceed more than 3 => add to violation count
- Non trigger framework code exists in triggers => add to violation
count
I'm not sure how to do this last one.
If you have any insight or feedback, let me know!
Thank you.
--
Caleb Knox
Endeveran
|