Class with sharing and without sharing in Salesforce

With Sharing - Enforce the sharing rules that apply to current user.
Without Sharing - Doesn't enforce the sharing rules.

If a class is not declared as either with or without sharing, the current sharing rules remain in effect. This means that if the class is called by a class that has sharing enforced, then sharing is enforced for the called class.

Default is without sharing.

Example:

public with sharing class CWith 
{
  // All code in this class operates with enforced sharing rules. 
    

  Account a = [SELECT . . . ];

  public void m() 
  { 
      . . . 
  }
  
}

public without sharing class CWithout 
{
  // All code in this class ignores sharing rules and operates  
    
  // as if the context user has the Modify All Data permission. 
    
  public void m() 
  {  
     . . . 

    // This call into CWith operates with enforced sharing rules 
    
    // for the context user. When the call finishes, the code execution  
    
    // returns to without sharing mode. 
    
    CWith.m();
  }


  public class CInner 
  {
    // All code in this class executes with the same sharing context 
    
    // as the code that calls it.  
    
    // Inner classes are separate from outer classes. 
    
    . . .

    // Again, this call into CWith operates with enforced sharing rules 
    
    // for the context user, regardless of the class that initially called this inner class. 
    
    // When the call finishes, the code execution returns to the sharing mode that was used to call this inner class. 
    
    CWith.m();
  }

  public class CInnerWithOut exends CWithout 
  {
    // All code in this class ignores sharing rules because 
    
    // this class extends a parent class that ignores sharing rules. 
    
  }
}

Cheers!!!

5 comments:

  1. By default class with sharing in salesforce.com

    ReplyDelete
  2. By Default Class is without sharing in Salesforce

    ReplyDelete
  3. Its not with nor without by default.Go through the doc"If a class isn’t declared as either with or without sharing, the current sharing rules remain in effect. This means that the class doesn’t enforce sharing rules except if it acquires sharing rules from another class. For example, if the class is called by another class that has sharing enforced, then sharing is enforced for the called class."

    ReplyDelete
    Replies
    1. By default it is without sharing with the exception when it is called by another class.

      Delete