Sub topic 2
Without Sharing and Inherited Sharing in Apex
Prerequisites: basic Apex classes, methods, and SOQL, plus Salesforce record access such as organization-wide defaults and sharing rules.
`without sharing`: bypassing record-level sharing on purpose
A class declared without sharing ignores record-level sharing for its SOQL queries and DML. It can access records that the running user cannot normally see or edit.
public without sharing class AccountAdminReader {
public static List<Account> getAllAccounts() {
return [SELECT Id, Name FROM Account];
}
}Use this only when the operation needs elevated record access, such as controlled administration or system calculations. The keyword does not automatically grant object permissions or field-level security. Those are separate controls.
What happens when you declare no keyword
A class with no sharing keyword inherits the sharing mode from its caller. This makes its behavior depend on the call path. A class called from with sharing normally respects record sharing. The same class called from without sharing can bypass it.
Because the behavior is not obvious from the class declaration, omitting the keyword can make security reviews and maintenance harder. Use inherited sharing when inheritance is the intended design.
Which sharing mode applies when classes call each other
Sharing applies to the class that defines the method. A caller does not force its own mode onto an explicitly declared class.
public with sharing class CaseController {
public static Integer countAllCases() {
return CaseCounter.countAll();
}
}
public without sharing class CaseCounter {
public static Integer countAll() {
return [SELECT COUNT() FROM Case];
}
}countAll() runs without sharing because CaseCounter declares without sharing, even though CaseController uses with sharing.
`inherited sharing`: letting the caller decide
inherited sharing makes the intent explicit. The class uses the caller's sharing mode. When it is the entry point of a transaction, it runs with sharing.
public inherited sharing class AccountRepository {
public static List<Account> findByName(String name) {
return [
SELECT Id, Name
FROM Account
WHERE Name = :name
];
}
}This pattern suits reusable services and repositories that should not secretly widen access.
Exercise
A with sharing class calls a class declared without sharing. Which mode applies to the called method?
Show answer
without sharing, because the method runs under the declaration of the class that defines it.