3

I am trying to resolve some of PMD warnings in Apex (Salesforce), currently I am working on this one UnusedLocalVariable and here is the code snippet where the problem is:

DateTime startDate = startDateOne;
String getData = 'SELECT data ' + 'FROM table ' + 'WHERE date = :startDate'

so..the problem is varible startDate is defined and used in query but it looks like the scanner can not recognize it because it is in a string 'WHERE date = :startDate', does anyone have an idea how to fix this?

Thanks in advance.

5

If you have to use dynamic SOQL like this, you'll need to ask PMD to suppress this "false positive". On the other hand, if you can use static SOQL that should avoid the issue:

DateTime startDate = startDateOne;
List<Table> records = [SELECT data FROM Table WHERE date = :startDate];

If you are dynamically defining the "data" or "table", you'll clearly need to stay using dynamic SOQL and tell PMD to suppress the false positive. There are a few different ways to do this.

I haven't tried it myself, but you could try:

@SuppressWarnings('PMD.UnusedLocalVariable')
theMethodSignature here() {
    DateTime startDate = startDateOne;
    String getData = 'SELECT data ' + 'FROM table ' + 'WHERE date = :startDate'

If that's too heavy handed, you can use the more targeted:

DateTime startDate = startDateOne; // TURN_OFF_WARNINGS
String getData = 'SELECT data ' + 'FROM table ' + 'WHERE date = :startDate'

As per feedback, the comment may need to be // NOPMD instead of // TURN_OFF_WARNINGS.

See the documentation for more details.

3
  • Thanks for answer, I can use it as a last resort but...I am not sure if there is any better solution then turning it off, I am not sure if there is maybe some other way to write an SOQL (without using a string inside it)?
    – mhdev
    Jul 28 at 8:45
  • @mhdev I've updated the answer.
    – Phil W
    Jul 28 at 9:10
  • 1
    I just want to add that in my case I had to use // NOPMD instead of // TURN_OFF_WARNINGS. I am not sure why but // TURN_OFF_WARNINGS did not work for me in more targeted cases. Anyway, thanks a lot for your explanation.
    – mhdev
    Jul 28 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.