With sharing & Without sharing keywords: Salesforce provides two important keywords: With Sharing and Without Sharing, which control whether Apex code respects the sharing rules of the current user or runs with administrative privileges. These keywords define the security context in which the code operates.
With Sharing Keyword
The With Sharing keyword ensures that the code respects the sharing rules that apply to the current user. This means that if the user does not have access to certain records based on the organization’s sharing settings, those records will not be accessible in the code.
Example:
public with sharing class MysharingClass {
// Code will enforce current user's
// sharing rules
}
In this example, the class MysharingClass
will respect the user’s sharing rules. If a user doesn’t have access to certain records due to sharing settings, the code will honor that restriction.
Without Sharing Keyword
The Without Sharing keyword ensures that the code does not enforce the sharing rules of the current user. It runs in system context, meaning it has access to all records, regardless of the user’s permissions.
Example:
public without sharing class NoSharing {
// Code won't enforce current user's
// sharing rules
}
In this case, the class NoSharing
will ignore sharing rules, allowing the code to access all records in the system, even those restricted from the current user’s view.
Best Practices:
- Use With Sharing when your code needs to respect a user’s permissions.
- Use Without Sharing sparingly, primarily when the business logic requires access to all records regardless of sharing rules.