Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Why, in the following code, is it declared as public with sharing?

public with sharing class ForgotPasswordController  {
    public String username {get; set;} 
    public String Domainname {get; set;} 
share|improve this question

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.

share|improve this answer

There are three types of sharing models: "with sharing", "without sharing", and "inherited sharing" (the third is default, and implicit). The sharing model affects DML operations and queries; when sharing is applied, queries return fewer records and DML operations may fail based on sharing rules. When sharing is not applied, all records can be queried and DML operations won't fail because of sharing (but, of course, can still fail because of validation rules, etc).

The implicit model is usually "without sharing", but sometimes it may be "with sharing" (e.g. from execute anonymous calls); when called from another class, it inherits the sharing model of the caller. Since these keywords only affect queries and DML operations, there's no specific reason why this class must be marked "with sharing"; it has no effect on this specific example.

The usual reasons why "with sharing" is included in a class are twofold: (1) it is a best practice to make sure that future changes to the class will honor sharing (i.e. so you don't forget to add "with sharing" to the class after you add a query), and (2) classes marked "without sharing" or implicit sharing will raise a security flag in the automated security scanner, which will have to be explained in a security review (when publishing to the AppExchange).

Adding the "with sharing" keyword makes sharing explicitly enabled, avoids the automated flagging that occurs with the security scanner, and eases the security review. However, if you need implicit sharing (e.g. the classes can be called from triggers, and needs to be without sharing in those cases), or if you need non-sharing (e.g. the code performs administrative work), then do feel free to use that model, but only after understanding the implications of using either model.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.