I’ve noticed that Batch Apex classes are all global, and the dev console returns an error if you just try to do a public/private class.
My understanding is that a global class is visible to all other code, which would make sense if I’m making a generic Batch Apex processor class that feed calls to other classes to (if you can even do something like that). But what about when the batch process you want to perform is included completely within the body of the batch class – whats the point of having it global in that case?
Separately, I noticed in the first example given on the Using Batch Apex doc, the global variables have a ‘final’ modifier. I’ve been having difficulty finding the documentation on this modifier. Can anyone explain to me what it means, and what it’s purpose is in this context?
Here’s the example from the documentation:
global class UpdateAccountFields implements Database.Batchable<sObject>{ global final String Query; global final String Entity; global final String Field; global final String Value; global UpdateAccountFields(String q, String e, String f, String v){ Query=q; Entity=e; Field=f;Value=v; } global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<sObject> scope){ for(Sobject s : scope){s.put(Field,Value); } update scope; } global void finish(Database.BatchableContext BC){ } }
Answer
A Database.Batchable
class has to be a top-level class (not an inner class) but can now be public
.
When Database.Batchable
was first available, implementors had no choice but to use the global
access modifier. For people creating managed packages, this had the very unfortunate consequence of making any Database.Batchable
part of the managed package’s API whether you wanted it to be or not. global
makes a class usable by code outside of a managed package; public
makes a class usable by any class within the managed package or within a non-packaged set of source code.
This error has been corrected so that you now have the choice of making the Database.Batchable
public
or global
and public
is the right choice most of the time. Unfortunately I don’t think the documentation has been updated.
private
not global
or public
is the right access modifier for fields most of the time. Sometimes final
is helpful in communicating intent to the reader and/or enforcing its constraint. But a more important point about fields in a Database.Batachable
implementation class is that state is not maintained in fields between invocations of the methods unless the implementation class is also marked as Database.Stateful
.
Attribution
Source : Link , Question Author : smohyee , Answer Author : Keith C