Skip to main content

APEX ACCESS MODIFIERS - With Sharing • Without Sharing

 APEX ACCESS MODIFIERS - With Sharing • Without Sharing


In Apex, access modifiers like with sharing and without sharing determine how a class enforces sharing rules (such as object-level and record-level security). These modifiers do not control visibility like public or private do — they control whether record-level access is respected.

APEX SHARING MODIFIERS

with sharing

  • Enforces the current user's sharing rules.

  • Only allows access to records that the user has permission to see.

  • Recommended for most business logic to respect security.


demo

without sharing

  • Ignores sharing rules (runs in system context).

  • Can access all records, regardless of user's access.

  • Use with caution, typically for admin-level operations or utilities.



Default Behavior (If Omitted)

If neither with nor without sharing is specified:

  • Default is "inherited" from the caller class if one exists.

  • If the class is run from anonymous Apex or triggers, it runs without sharing by default.


 Key Notes

  • with sharing does not enforce object or field-level security (use stripInaccessible or Security.stripInaccessible() for that).

  • Triggers always run in system context (like without sharing).

  • Consider using inherited sharing (available from API 44.0+) to inherit sharing context dynamically.


✅ Summary Table

ModifierEnforces Sharing RulesUse Case
with sharing✅ YesMost business logic
without sharing❌ NoAdmin tasks, internal utilities
inherited sharingDepends on callerFlexible/shared utility logic
No modifierDepends on contextRisky—explicit is better