With Sharing Keyword: When you want to enforce sharing rules that apply to the
current user while executing an Apex class, you must use With Sharing keyword for the
class. Without With Sharing keyword, the class would execute in system context, i.e. the
sharing rules will not be applied for the current user. So the records that are not suppose to be
accessed by the current user will be exposed.
Example:
The only exceptions to this rule are Apex code that is executed with the
executeAnonymous call and Connect in Apex. executeAnonymous always executes
using the full permissions of the current user.
Example:
public with sharing class sharingClass {
// Code here
}
Without Sharing Keyword: It ensures that the sharing rules of the current user are
not enforced. So why do we have to explicitly define Without Sharing as if you don't
mention any keyword, it will enforce sharing rules as it will execute in system context? The
answer is when the class(no sharing is mentioned ) is called from another class that is
declared using With Sharing then sharing is enforced for the called class. To avoid such
situation, we can explicitly define Without Sharing so that the class (no sharing is
mentioned ) will run in system context.
Example:
public without sharing class nosharing {
// Code here
}
Important things to Remember about Sharing Keywords:
- The Sharing settings are applied on the class where the method is defined, not of the
class where the method is called. For example, if a method is defined in a class with With
Sharing and the method is called from a class declared with Without Sharing, the method
executes with sharing rules enforced.
- A class isn’t declared as either with or without sharing, the class doesn’t enforce sharing
rules for the current user except when it acquires sharing rules from another class. For
example, if the class is called by another class that has with sharing keyword, then sharing is
enforced for the called class.
- Both inner classes and outer classes can be declared as With Sharing. The sharing
setting applies to all code contained in the class, including initialization code, constructors,
and methods but Inner classes do not inherit the sharing setting from their container class.
- A class can inherit sharing setting from a parent class when one class extends or
implements another.
No comments:
Post a Comment