Upgrade to Pro — share decks privately, control downloads, hide ads and more …

What's new in ApexLib?

What's new in ApexLib?

Chris Peterson

June 04, 2014
Tweet

More Decks by Chris Peterson

Other Decks in Programming

Transcript

  1. How do we query? It all starts off so simple:

    Contact notBob = [SELECT Name, Id FROM Contact WHERE Name != ‘Bob’ LIMIT 1];
  2. How do we query? But it can get ugly fast:

    //ewww String soql = ‘SELECT ‘; for(Integer i = 0; i< fieldList.size(); i++){ soql += fieldList + ‘, ‘; } soql = soql.substring(0,soql.length()-2); soql += conditions != null && conditions.trim().size() > 0 ? ‘ WHERE ‘ + soqlConditions : ‘’; soql += limit != null && limit.trim().size() > 0 ? ‘ LIMIT ‘+limit; List<Contact> nonBobs = Database.query(soql);
  3. Introducing QueryFactory • Object-oriented. No string building. • Enables flexible

    selector layers. • Idempotent operations (where sane). • Field-set friendly. • Package-friendly (implies namespaces)
  4. What’s so bad about string building? • Did you see

    that earlier slide? • Fails late, well after when errors were introduced. • Stream-like: you can’t (easily) amend a previous clause.
  5. Why not apex-commons SOQLBuilder? Initially planned to, but… • Massive,

    verbose. • No updates in quite a while. • Not idempotent, reduces encapsulation.
  6. Results in: SELECT Name FROM Contact Limit 5 In it’s

    simplest form: new fflib_QueryFactory(Contact.SObjectType) .selectField(‘name’) .setLimit(5) .toSOQL(); So how do I use it?
  7. fflib_QueryFactory qf = new fflib_QueryFactory(Contact.SObjectType) .selectField(Contact.SObjectType.fields.name) .selectField(‘name’) //ignored: name already

    selected .selectFieldSet( Schema.SObjectType.Contact.fieldSets.MyFieldSet ) .setLimit(5); qf.setCondition(‘Name != “Bob”’); qf.setLimit(10); //overrides the earlier limit Results in: SELECT Name, <MyFieldSet’s fields> FROM Contact WHERE Name != “Bob” LIMIT 10 With a field set
  8. When should I use it? • Field sets. • Dynamic

    queries. • Extensible selector classes.
  9. When should I go another route? • When queries are

    static. • When performance is more critical than code quality. • When you need aggregations. • Weird SOQL edge cases, like toLabel().
  10. Future Plans • Bind variable support • Object and field

    read permission checks • Better cross-object field selects • Support for aggregations • Object-oriented where clauses (#safeharbor)