25

After I posted this question, I found a similar post that seemed to answer it: Variable scope - database.query() has access to variables not in scope. I'll leave this in place for now, as I am not sure how to mark my own question as a duplicate

In attempting to debug a SOQL query error, I encountered a strange behavior with Database.query and bind variables. Specifically, when I run this code:

String userQuery = 'SELECT Id FROM User';
if (true) {
    List<String> firstNames = new List<String>{'James','Joe'};
    userQuery += ' WHERE FirstName IN :firstNames';
}
Database.query(userQuery);

the Database.query statement executes with no errors, despite the fact that the variable firstNames does not exist in its context. However, when I add an else clause:

String userQuery = 'SELECT Id FROM User';
if (true) {
    List<String> firstNames = new List<String>{'James','Joe'};
    userQuery += ' WHERE FirstName IN :firstNames';
} else {
    List<String> firstNames;
}
Database.query(userQuery);

I receive a null object reference exception. It seems like Salesforce is checking to see if the variable is only declared once beforehand and, if so, uses its value in the context it was declared. This seems strange to me, so I was wondering if anybody here has any insight into what is going on under the hood.

  • Why did you delete this question? Seems like a good one! – Adrian Larson Mar 14 '17 at 21:19
  • @AdrianLarson I found another question very soon after I posted this one that seemed to answer what I was asking: salesforce.stackexchange.com/questions/113091/…. I'm not sure if there is a way for me to indicate that this question is a duplicate myself. – Johnathan Ashley Mar 14 '17 at 21:30
  • This question still sheds some new light (or doubt?) on the mechanics of that scope. I find it distinct, though we'll see what other members of the community decide. – Adrian Larson Mar 14 '17 at 21:35
  • It is even more odd that it sees the variable inside the else as anything outside the else does not have access to that variable – Eric Mar 14 '17 at 21:49
4

I have confirmed that this is a bug that has been logged at Salesforce, and will presumably be fixed at some point. You should not rely on this behavior, as it may break in a future version. Always make sure your variables are in scope.

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.