Sub topic 3
Inner Classes and Sharing
Assume you know basic Apex classes, methods, SOQL, and Salesforce record access. This chapter focuses on how sharing interacts with nested classes and permissions.
Inner classes and sharing
An inner class is a class declared inside another class. An inner class does not automatically inherit the outer class's sharing keyword. Declare the intended mode explicitly.
public with sharing class CaseService {
public without sharing class BroadReader {
public static List<Case> readCases() {
return [SELECT Id, Subject FROM Case];
}
}
}BroadReader can query records without applying record-level sharing, even though CaseService uses with sharing. This is one reason reviewers inspect inner classes separately.
Sharing is not CRUD or field-level security
Sharing controls which records a user can access. CRUD controls whether the user can create, read, update, or delete an object. Field-level security controls access to individual fields.
A with sharing class can still expose fields or perform operations that the user’s profile or permission sets do not allow.
Enforcing permissions with user-mode queries and DML
Use user-mode operations when code must enforce object permissions and field-level security as well as record sharing.
public with sharing class ContactService {
public static List<Contact> findContacts() {
return [
SELECT Id, LastName, Email
FROM Contact
WITH USER_MODE
];
}
public static void saveContacts(List<Contact> contacts) {
Database.update(contacts, AccessLevel.USER_MODE);
}
}The class declaration handles record-level sharing. USER_MODE adds the user’s object and field permissions.
Choosing the right keyword
- Use
with sharingfor controllers and most application services. - Use
inherited sharingfor reusable classes whose behavior should follow the caller. - Use
without sharingonly for a documented business requirement, such as controlled administrative processing. - Avoid leaving the keyword out. The resulting behavior depends on the call context and can be unclear during review.
Testing and pitfalls
Test with System.runAs and users who have different record access. Verify both visible-record results and permission failures. Review every class in the call chain, including inner classes. Do not assume that a with sharing caller makes every helper secure.
Exercise
A with sharing class calls a without sharing inner class. Which class controls the inner query?
Show answer
The inner class controls its own method. Its without sharing declaration can bypass record-level sharing.