The future annotation is a great feature on the Salesforce Platform to allow you to execute custom logic asynchronously. I often use them to perform callouts within the context of a database trigger. However, one of the restrictions of future annotations is that you can not pass sObjects or objects as arguments to the annotated method. I regularly use encapsulation to pass a collection of parameters, or even an sObject, but this won’t work in @future method:
But thankfully there is a way you can do. The secret sauce is the JSON serialize|deserialize methods.
Take the example of an AddressHelper object referred to above. This is encapsulated convenience object to help me pass around address details. (note:For simplicity, this helper object just includes strings, but it could easily include other types including objects, sobjects, collections etc.)
Using the JSON serialize method I can easily pass this to an @future method.
And then, within my future method, all I need to do is deserialize the object, and you are good to go.
That’s it. JSON.serialize|deserialize makes it amazingly simple to pass objects, even ones with complex nested relationships, to @future annotated methods. There are time though that a particular object can not be serialized due to the underlying inheritance structure. One such example is the Pattern class in Apex.
To handle these outliers, I often create my own custom getSerializable() method on my custom object.
That’s about it. You can grab the complete code for the examples above as a gist here.