Q: What’s batchable Apex code?
Since we’re already on this kick of writing about the weird, wonderful, and whimsical aspects of Argentine society, today we’ll talk about cuotas. More specifically, let’s chat about paying in cuotas, and how this reminds me of how we can use batchable Apex code in those moments when we just simply can’t afford the number we see on the pricetag.
One lesson we can learn from economics is that if there is a demand for a product or service, that product or service will exist. Even if I don’t have a credit card, I still may want, nay expect, access to credit — the ability to buy something today for $1000, and pay for it over the next, 3, 6, or 12 months. In Argentina, these plans of divided payments are called cuotas.
As a general rule of thumb, we can assume that the higher someone’s level of wealth, the less they need to depend on credit. Follow this rule down the economic ladder, and you can see that in a country like Argentina where incomes are modest, you can imagine the need for credit is both high and that the purchases made on credit can be surprisingly small. A house and a car, of course, but what about a new set of tupperware containers, your weekly groceries, your monthly cellphone bill?
Optimism in Batches
At first this stunned me, because the terms of cuota payments are, putting it lightly, lousy. After more thought, I started to understand that cuotas were a way of exercising optimism. They provided a way of saying “I don’t know today, but I think I can figure it out tomorrow.” In other words, when we buy something on credit or with a fixed payment plan, we’re conceding that we can’t afford it all right now. We’re saying “let’s do this in parts to smooth things out.”
Batchable Apex is the exact same. Often as a developers, we’ll need to write code which operates against a huge set of records, potentially of multiple objects. Well, in the face of governor limits, we may not be able to afford to process all of those records at once. Furthermore, even if we could do everything in one massive operation, if a single record caused a failure in our code the entire operation could fail.
Batchable Apex is just regular old Apex which implements the “Batchable” interface. I won’t explain what an interface is here, but to make something batchable we include three methods,
start method, we tell Salesforce which records we’ll be working with by creating a SOQL query.
execute, we do the work — we manipulate, update, create, delete, whatever we need to get done, we put it in here.
We finish with
finish, a method which will run once all the processing is complete. This could send the administrator an email, for example, with a status of how everything went.
Luckily for you, if you’d like to learn more, see the code in action, or implement your own batchable Apex class, I’ve written a post and created a video showing the process in much much more depth.
That’s all, cheers! Check out the other Conversations here.