8

Can anybody tell me about the with sharing and without sharing of apex class ?

Why we can use it ?

If we are not specify the keyword with sharing or without sharing which keyword set by default for that class ? (With sharing or without sharing)

Thanks.

1

1 Answer 1

8

Default - Without Sharing

Now, Apex class always execute in system context i.e. Apex code has access to all objects and fields irrespective of the logged in User. Example - lets consider you have VF page in which you are showing certain fields as columns. Lets see one column says "Sales Rep Performance" which displays a flag in red, green and yellow. Now ideally this field should not be visible whenever a Sales Rep accesses this page (consider this as business requirement). But it is always visible if the class has no keyword specified or if a class has without sharing specified.

Now once the class is "with sharing" the object permissions, field-level security, sharing rules are applied for the current user and fields which should not be visible/accessible and not visible or accessible.

Important -

  1. if a method is defined in a class declared with 'with sharing' is called by a class declared with 'without sharing', the method will execute with sharing rules enforced.
  2. The class doesn’t enforce sharing rules except if it acquires sharing rules from another class. Ex. Class A (with sharing) calls a method from Class B(Without sharing) then complete context is 'with sharing'
  3. Inner classes do not inherit the sharing setting from their container class.
3
  • 2
    Are you sure that Object level security and FLS are enforced by using "With Sharing" keyword? Commented Jan 28, 2020 at 10:34
  • 3
    CRUD and FLS are never enforced by "with sharing", only record sharing can be enforced this way and you can care about CRUD and FLS permission and validate it on your own. Ex. Class A (with sharing) calls a method from Class B(Without sharing) then complete context is 'with sharing' - this is also not true. The sharing setting of the class where the method is defined is applied, not of the class where the method is called. Eg., if a method is defined in a class declared with with sharing is called by a class declared with without sharing, the method executes with sharing rules enforced.
    – jm.
    Commented Feb 14, 2021 at 13:29
  • With sharing does not enforce FLS/CRUD Permissions! Commented Nov 21, 2023 at 14:02

Not the answer you're looking for? Browse other questions tagged .