At Dreamforce 2013 I’ll be giving a presentation called Introduction to the Flow Factory Design Pattern. This material is based on the same subject I cover in my Pluralsight course: Design Patterns – Part 2 and also have written about on the developer force wiki. I’ve been working on some exciting improvements to the pattern that will be included in the presentation and I look forward to sharing the new material.

From a high-level, this pattern provides a stateful approach to handling flowchart-style business logic in Apex. It’s “headless,” which means that unlike Visual Workflow, it doesn’t involve user input at each step. One of the key challenges that this pattern addresses is the order of execution constraints placed on performing DML and making callouts in the same execution context. Put simply, you can’t save data (execute DML) and then make a callout in the same context. However, you can save all necessary data after all callouts have completed. This is also true for sending emails, meaning that you can’t send an email and then make a callout, though you can send emails as long as no additional callouts will be performed in the same context.

It’s very common to need to save information after making a callout to an external API. Even if the data being retrieved isn’t meant to be stored in Salesforce, often it’s useful to save callout results for instrumentation and/or debugging purposes. Say for example you have two callouts that are being made in the same context to two different remote sites (#1 is Twitter and #2 is Facebook, for example). What happens if the first call fails and returns detailed information about the failure? It would be nice to save the data or perhaps email it immediately to investigate the issue further. But either saving data or sending an email will break the second call – unless those actions are postponed.

One way to handle this is to use if/else branching. This seems to make sense logically, but the resulting code is often hard to maintain and inflexible. And anything beyond a trivial flow where multiple steps are involved that’s handled with if/else branching can produce code that resembles a fine plate of spaghetti. In other words, it can get messy.

Please join me on Wednesday, November 20th for an introduction to the Flow Factory design pattern! The presentation will be in Moscone Center West – 2011 at 11:45AM.

Hope to see you there!


-Adam Purkiss