Sharing, Without Sharing, and Inherited Sharing Keywords in Apex #inSalesforce

Sharing, Without Sharing, and Inherited Sharing Keywords in Apex


-With Sharing or Without Sharing Keywords on a class to specify whether Sharing Rules must be enforced or not.

-Inherited sharing keyword on a class to run the class in the sharing mode of the class that called it.


With Sharing:

  • Used when declaring a class to enforce sharing rules of the current user.
  • Ensures that Apex code runs in the current user context. 
  • Use this mode as the default unless your use case requires otherwise.


Syntax:

public with sharing class sharingClass {
   // Code here
}


Without Sharing:

  • Used when declaring a class to ensure that the sharing rules for the current user are NOT enforced that is you can explicitly turn off sharing rule enforcement when a class is called from another class that is declared using with sharing.
  • Use this mode with caution. Ensure that you don’t inadvertently expose sensitive data that would normally be hidden by the sharing model. This sharing mechanism is best used to grant targeted elevation of sharing privileges to the current user.
  • For example, use without sharing to allow community users to read records to which they wouldn’t otherwise have access.


Syntax:

public without sharing class noSharing {
   // Code here
}



Inherited Sharing:

  • Used when declaring a class to enforce the sharing rules of the class that calls it.
  • Use this mode for service classes that have to be flexible and support use cases with different sharing modes while also defaulting to the more secure with sharing mode.


Syntax:

class -

public inherited sharing class InheritedSharingClass {
    public List<Contact> getAllTheSecrets() {
        return [SELECT Name FROM Contact];
    }
}

page - 

<apex:page controller="InheritedSharingClass">
    <apex:repeat value="{!allTheSecrets}" var="record">
        {!record.Name}
    </apex:repeat>
</apex:page>



Reference; https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_keywords_sharing.htm#:~:text=Use%20the%20without%20sharing%20keyword,is%20declared%20using%20with%20sharing%20.

Comments