Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

Best Practices for Controllers and Controller Extensions

Enforcing Sharing Rules in Controllers
Like other Apex classes, custom controllers and controller extensions run in system mode.
Typically, you want a controller or controller extension to respect a user’s organization-wide defaults, role hierarchy, and sharing rules. You can do that by using the with sharing keywords in the class definition. For information, see “Using the with sharing, without sharing, and inherited sharing Keywords” in the Apex Developer Guide.

If a controller extension extends a standard controller, the logic from the standard controller doesn’t execute in system mode. Instead, it executes in user mode, in which the permissions, field-level security, and sharing rules of the current user apply.

Note

Controller Constructors Evaluate Before Setter Methods
Do not depend on a setter method being evaluated before a constructor. For example, in the following component, the component's controller depends on the setter for selectedValue being called before the constructor method:
Since the constructor is called before the setter, selectedValue will always be null when the constructor is called. Thus, EditMode will never be set to true.
Methods may evaluate more than once — do not use side-effects
Methods, including methods in a controller, action attributes, and expressions, may be called more than once. Do not depend on evaluation order or side-effects when creating custom methods in a controller or controller extension.