Hope you are well and doing well in these times,Below is a common scenario to take some set of sObject records, execute some processing such as making a callout to an external REST endpoint or perform some calculations and then update them in the database asynchronously. . The following code takes a collection of Account records, sets the parentId for each record, and then updates the records in the database.
My questions are:-
A) Why i need to set the parentId for each record for Queueable Apex?
B) Why i cant use public identifier (mind you i know differences between public and private identifier :)) but why here we used private in Queueable Apex and then we have to set the values?
public class UpdateParentAccount implements Queueable {
private List<Account> accounts;
private ID parent;
public UpdateParentAccount(List<Account> records, ID id) {
this.accounts = records;
this.parent = id;
}
public void execute(QueueableContext context) {
for (Account account : accounts) {
account.parentId = parent;
// perform other processing or callout
}
update accounts;
}
}
Source:- https://trailhead.salesforce.com/en/content/learn/modules/asynchronous_apex/async_apex_queueable
Setting of a parent ID is an example of a task that can be done asynchronously. This is a somewhat poorly chosen example because the same task could be done synchronously without Queuable. (If there are a lot of Account records being updated then moving this task to async might be a good idea).
Public versus private - making a field private is a best practice as a way of encapsulating data in a class. It is used to hide the values or state of a structured data object inside a class, thus preventing direct access to them. In case of a Queuable, this is kinda like a utility class that will be used in a very specific context so you could make the variables public and remove the constructor.