Activity Forums Salesforce® Discussions Apex in salesforce

  • Apex in salesforce

    Posted by madhulika shah on August 29, 2018 at 1:09 pm

    In class declaration if we don’t write keyword “with sharing” then it runs in system mode then why keyword “without sharing” is introduced in apex?

    shariq replied 6 years, 3 months ago 3 Members · 2 Replies
  • 2 Replies
  • Parul

    Member
    August 30, 2018 at 5:31 am

    Hello Madhu,

    Apex class always execute in system mode 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 -

    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.
    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'
    Inner classes do not inherit the sharing setting from their container class.

    So,  ''without sharing" keywords to ensure that Apex scripts do not enforce the sharing rules of the running user.

    Thanks

    Parul Singh

  • shariq

    Member
    September 14, 2018 at 10:26 pm

    Hi,

    If not declared explicitly, classes are always With Sharing.

    It is important to understand that in both cases (With or Without Sharing), Apex runs in System Mode, so it wouldn't respect things like Field Level Security.

    Use With Sharing when the User has access to the records being updated via Role, Sharing Rules, Sales Teams - any sort of sharing really.

    Without Sharing is reserved for cases where the User does not have access to the records, but there is a need to update them based on user input.

    Also the With / Without Sharing commutes and if a class doesn't have an explicit declaration, the sharing context of the calling class is inherited.

    Hope this helps.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos