Sub topic 12
Choosing the right keyword for each kind of class
This chapter assumes you know what each keyword does (with sharing, without sharing, inherited sharing). It also assumes you know how the mode follows a call chain, and that sharing is separate from object permissions and field-level security. Here you decide which keyword to put on each kind of class you write.
Start from the entry point
A class's sharing mode only matters at runtime, and it is set by whoever started the transaction. So the question for every class is who might call it. There are two kinds of callers:
- Entry points are classes the platform calls directly:
@AuraEnabledcontrollers, Visualforce controllers, REST resources, invocable methods, batch and queueable classes, and trigger handlers. - Internal classes are called by other Apex. This covers services, selectors, repositories, and utilities.
The rule of thumb is to make entry points explicit and let internal classes follow them. Entry points declare with sharing unless you have a documented reason not to. Internal classes declare inherited sharing. A narrow without sharing class is the exception, for the specific places where bypassing sharing is the point.
Summary by class type
| Kind of class | Recommended keyword | Reason |
|---|---|---|
| `@AuraEnabled` or Visualforce controller | `with sharing` | It is the entry point, so it sets the mode for everything below it. |
| REST resource, invocable method | `with sharing` | The caller is an external or flow user who should see only their own data. |
| Service or business-logic class | `inherited sharing` | It should respect whatever the caller chose. |
| Selector or repository (data access) | `inherited sharing` | Queries should match the caller's mode. |
| Trigger handler | `inherited sharing` | Triggers run in system mode, so the handler follows the triggering context. |
| Batch or queueable job | Decide explicitly, usually `with sharing` or `inherited sharing` | A scheduled job has no interactive user, so the mode must be a deliberate choice. |
| Privileged operation (duplicate check, rollup across all records) | `without sharing`, as a small isolated class | It needs wider visibility than the user has. |
| Utility with no queries or DML | Any, but `inherited sharing` is a safe choice | It does not touch data, so the keyword rarely matters. |
Controllers: be explicit
A controller is the first Apex class in the transaction, so its keyword is the one that counts. If you omit the keyword on an entry point, the class runs without sharing. That default is easy to miss in review, so declare the keyword.
// AccountController.cls
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> searchAccounts(String term) {
return AccountService.search(term);
}
}Putting with sharing here means the whole chain below it is protected, as long as every class in the chain follows the caller.
Services and repositories: follow the caller
A service has no idea who will call it. A nightly job might call it, and so might a controller. Hard-coding with sharing would make the nightly job unable to see records it legitimately needs. Hard-coding without sharing would leak records to every user-facing caller. inherited sharing avoids both problems.
// AccountService.cls
public inherited sharing class AccountService {
public static List<Account> search(String term) {
if (String.isBlank(term)) {
return new List<Account>();
}
return AccountRepository.findByNameLike(term);
}
}// AccountRepository.cls
public inherited sharing class AccountRepository {
public static List<Account> findByNameLike(String term) {
String pattern = '%' + term + '%';
return [
SELECT Id, Name
FROM Account
WHERE Name LIKE :pattern
WITH USER_MODE
LIMIT 50
];
}
}The repository uses inherited sharing for record access and WITH USER_MODE for object and field permissions. Those are two separate protections, and a user-facing path needs both. The term value is passed as a bind variable, so it cannot change the structure of the query.
inherited sharing is better than leaving the keyword off. With no keyword, a class used as an entry point runs without sharing. With inherited sharing, the same entry-point use runs with sharing. The explicit keyword fails safe if someone later wires the class directly to a Lightning component or an API.
Without sharing: small, isolated, justified
Sometimes the user legitimately cannot see data that the logic needs. A common case is checking for a duplicate across the whole org when private sharing hides other users' records. The safe pattern is to put only that logic in a separate without sharing class. Return the least information that answers the question.
// DuplicateAccountCheck.cls
public without sharing class DuplicateAccountCheck {
// Returns only a Boolean, so no record data crosses the sharing boundary.
public static Boolean nameExists(String name) {
return [SELECT COUNT() FROM Account WHERE Name = :name] > 0;
}
}// AccountCreator.cls
public with sharing class AccountCreator {
public static Id create(String name) {
if (DuplicateAccountCheck.nameExists(name)) {
throw new AccountCreatorException('An account named ' + name + ' already exists.');
}
Account a = new Account(Name = name);
Database.insert(a, AccessLevel.USER_MODE);
return a.Id;
}
public class AccountCreatorException extends Exception {}
}The privileged work happens in a class a reviewer can read in ten seconds. The insert still runs under the user's permissions. Each method runs under the sharing mode of the class that defines it, so AccountCreator.create stays in with sharing while nameExists runs without sharing.
Keeping `without sharing` from spreading
A without sharing class is safe only while its callers stay careful. Three habits help.
- Keep it small. One purpose per class, with a comment saying why sharing is bypassed.
- Do not subclass or extend it casually. Giving the class broad public methods makes it a general-purpose back door.
- Do not put a data-access class under it. If your repository is
without sharing, every service that uses it loses protection, and controller keywords no longer help. Keep repositories oninherited sharing.
Batch and scheduled jobs
Batch and queueable jobs often run with no interactive user. They run as the user who scheduled or enqueued them, and that user's sharing may not match what the job needs. Pick the keyword deliberately.
- If the job processes data on behalf of one user, use
with sharingorinherited sharingso it matches that user. - If the job maintains org-wide data, such as a nightly rollup,
without sharingmay be the right answer. Document it, and make sure no user can trigger it with their own input.
Trigger handlers
Triggers run in system context, so a trigger itself does not apply sharing. A handler class called from a trigger can declare a mode. inherited sharing is a reasonable default because the transaction's origin already decided the user context. Use without sharing only for specific lookups that need wider visibility, and keep those in a small separate class as above.
Common mistakes when choosing
- Copying
without sharingfrom an example. Examples often use it to avoid access errors during development. Remove it before production. - Putting
with sharingon everything. This looks safe, but awith sharingservice called from a system job can silently miss records, which causes data bugs that are hard to trace. Useinherited sharingfor services. - Relying on the keyword for field security.
with sharingdoes not hide fields. AddWITH USER_MODEorAccessLevel.USER_MODEwhere users must be limited to fields and objects they have permission to use. - Assuming an inner class follows its outer class. Inner classes do not inherit the sharing declaration of their container. Declare the keyword on the inner class if it queries data.
Exercise
A team has a LeadScoringService class used by an @AuraEnabled controller and by a nightly batch job that must score every lead in the org. The service declares with sharing, and the batch job misses leads owned by other users. What keyword change fits best, and what must be true about the batch job?
Show answer
Change LeadScoringService to inherited sharing so it follows its caller. The controller keeps with sharing, so users see only their own leads. The batch class must itself declare without sharing, because an inherited sharing service takes that mode from the batch class. Document why the batch bypasses sharing, and make sure users cannot trigger it with arbitrary input. Do not make the service without sharing, because the controller path would then expose every lead to every user.
Exercise
A repository class declares no sharing keyword. A Lightning component calls it directly through an @AuraEnabled method on the same class. Which sharing mode applies, and what is the minimal fix?
Show answer
It runs without sharing, because a class with no keyword that serves as the entry point does not enforce sharing. The minimal fix is to declare with sharing on the class. Better, move the @AuraEnabled method into a with sharing controller and mark the repository inherited sharing.