Sub topic 9
Inner classes and sharing
An inner class is a class declared inside another class. Apex allows one level of nesting. This chapter assumes you know how with sharing, without sharing, and inherited sharing behave on top-level classes. The question here is how those keywords behave when classes are nested.
The rule: inner classes do not inherit from their outer class
An inner class does not take its sharing mode from the class that contains it. Each class, outer or inner, gets its sharing mode from its own declaration. The sharing setting applies to everything inside that class: initialization code, constructors, and methods.
This surprises many developers, because the inner class is physically inside the outer class's braces. A with sharing outer class does not make its inner classes with sharing.
| Outer class | Inner class declaration | Sharing mode used by the inner class's code |
|---|---|---|
| `with sharing` | `with sharing` | Enforces the user's record access |
| `with sharing` | `without sharing` | Ignores record-level sharing |
| `without sharing` | `with sharing` | Enforces the user's record access |
| `with sharing` | `inherited sharing` | Takes the mode of whichever class called it |
| `with sharing` | no keyword | Follows the omitted-keyword behavior from the earlier chapter, not the outer class |
Because of the last row, declare a keyword on every inner class that runs queries or DML. Don't leave it to the outer class's setting.
Seeing it in code
The next example is a with sharing service with a private inner class that opts out of record-level sharing for one narrow job.
public with sharing class CaseService {
// Runs under the outer class: respects the user's record access
public static Integer countVisibleCases() {
return [SELECT COUNT() FROM Case];
}
// Delegates to the inner class: the count ignores record-level sharing
public static Integer countAllCases() {
return new UnrestrictedCaseReader().countAll();
}
private without sharing class UnrestrictedCaseReader {
public Integer countAll() {
return [SELECT COUNT() FROM Case];
}
}
}Suppose the running user can see 10 of 100 cases. CaseService.countVisibleCases() returns 10. CaseService.countAllCases() returns 100, because countAll is defined in a without sharing class. The outer class's with sharing declaration has no effect on that method.
Inner classes cannot declare static methods or static variables in Apex. That is why the example creates an instance of the inner class. Only top-level classes can have static members.
Which sharing mode a method uses
The call-chain rule from the previous chapter still applies, and inner classes follow it too. A method runs under the sharing mode of the class that defines it. The class that calls it does not matter.
The diagram shows the example above when a user calls countAllCases().
Control returns to CaseService after the inner method finishes. Any query that CaseService itself runs next is back under with sharing. Sharing mode applies per method execution, not per transaction.
Using inner classes deliberately
Because the inner class has its own setting, you can use it to confine the risky part of a design. This is the main reason to nest sharing-sensitive code.
Isolate the privileged operation
Put the one operation that must bypass sharing in a small, named, private inner class. Keep the outer class with sharing. A reviewer then sees exactly where record-level sharing is bypassed, and the bypass can't be called from outside the outer class.
Make the inner class private. If it is public, any code in the org can create it and call its methods. That would turn a deliberate exception into a general-purpose bypass.
Keep data holders out of the discussion
Inner classes that only hold data, such as wrapper classes for a Lightning component or a JSON response, run no queries and no DML. Their sharing setting has no effect on the data they hold. Adding a keyword still does no harm, and some teams require one for consistency.
public with sharing class OpportunitySummaryController {
public class Summary {
public String name;
public Decimal amount;
}
public static List<Summary> getSummaries() {
List<Summary> result = new List<Summary>();
for (Opportunity o : [SELECT Name, Amount FROM Opportunity LIMIT 50]) {
Summary s = new Summary();
s.name = o.Name;
s.amount = o.Amount;
result.add(s);
}
return result;
}
}The query runs in getSummaries, which belongs to the with sharing outer class. The Summary class only carries values, so its own sharing mode never comes into play.
Using `inherited sharing` on an inner class
An inner class can be declared inherited sharing. It then uses the mode of the class that calls it. If the inner class is the entry point of a transaction, it runs with sharing. This is useful for a small reusable helper that lives next to the code that uses it, and whose mode should follow its caller.
public without sharing class ReportJob {
public static Integer run() {
// The inner class is called from a without sharing class,
// so inherited sharing resolves to without sharing here.
return new Counter().countAccounts();
}
private inherited sharing class Counter {
public Integer countAccounts() {
return [SELECT COUNT() FROM Account];
}
}
}If ReportJob were declared with sharing, the same Counter would enforce the user's record access. Its behavior depends on who calls it, which is the point of inherited sharing.
Extending and implementing
Inner classes follow the same inheritance rules as other classes. A class that extends or implements another class can pick up its parent's sharing setting when it declares no keyword of its own. Don't rely on that for security-sensitive code. Declare the keyword on the subclass so the behavior is visible where the code is written.
Common errors with inner classes
- Assuming the outer keyword covers the inner class. A
with sharingouter class containing awithout sharinginner class is easy to miss in review. Search forwithout sharinginside nested code, not only at the top of files. - Leaving the keyword off an inner class that queries data. The behavior then depends on the omitted-keyword rules, which vary with how the code is called. Always declare one.
- Making a bypass inner class public. This exposes the unrestricted behavior to every caller. Use
private, or@TestVisible privateif tests need access. - Trying to add a static helper inside an inner class. The compiler rejects static methods and variables in inner classes. Move the helper to the outer class, or create an instance as shown above.
- Forgetting the sharing keywords do not cover permissions. A
with sharinginner class still allows queries on fields the user cannot read. UseWITH USER_MODEorAccessLevel.USER_MODEfor that, as covered in the later chapters.
Summary of the rules
- Each class, outer or inner, has its own sharing declaration.
- Inner classes do not inherit the keyword from the class that contains them.
- A method runs under the mode of the class that defines it, even when it is called from a class with a different mode.
- Inner classes can use
with sharing,without sharing, orinherited sharing. - Inner classes cannot have static methods or variables, so callers need an instance.
- Keep any bypass in a small, private, clearly named inner class.
Exercise
A top-level class OrderService is declared with sharing. It contains an inner class Archiver with no sharing keyword, and Archiver queries Order records. A teammate says, "The query respects the user's record access because the outer class is with sharing." What is wrong with this reasoning, and how would you fix the code?
Show answer
Inner classes do not inherit the sharing setting from their outer class, so OrderService's with sharing declaration does not apply to Archiver. With no keyword on Archiver, its behavior follows the omitted-keyword rules, which depend on how it is called. Fix it by declaring the keyword on the inner class explicitly: private with sharing class Archiver to enforce the user's record access, or private inherited sharing class Archiver if it should follow its caller. Then the mode is visible at the class and does not depend on call context.
Exercise
ReportService is with sharing. It contains a private inner class FullCounter, declared without sharing, with a method count() that runs SELECT COUNT() FROM Lead. ReportService also has its own method countMine() with the same query. The running user can see 5 of 50 leads. What do countMine() and new FullCounter().count() return when called from ReportService?
Show answer
countMine() returns 5, because it is defined in the with sharing outer class. new FullCounter().count() returns 50, because the method is defined in a without sharing inner class and runs under that class's mode, even though ReportService called it.