Mar 11, 2013

How Many Lines of Code Does It Take To Create a Set of Ids?

I was recently cleaning up a piece of hideous code (feel free to replace with an expletive - it was that bad) that we took over from a different consultancy. The original object infrastructure involved many custom objects with several of them being relationship objects (i.e. many to many). Even after I fixed occurrences of SOQL and DML inside loops, eliminated unnecessary looping, and other generally bad design patterns, the bigger requests were hitting the 200001 executed statements limit error. I had to dig deeper and eliminate more loops.

Since this class was dealing with so many relationship tables, there were several places were the code was constructing lists of ids based on a lookup field values. For example. Let's say that you have the Id of a record in obj__c, but what you really need is a Set of all the lookup values in the field LookupToDiffObj__c on the obj__c object. Normally you would use a couple of soql queries and some looping to get it done, resulting in a few hundred lines of executed code. What if you had to do that several times for several objects for thousands of records at a time?

That's what I needed to solve, and after putting some thought into it I came up with the following handy pattern that achieves all that in one line of executable code (that counts as 2 SOQL queries).