Setter Methods
Setter Methods in Salesforce Apex are methods on a controller class that receive values from user input on a Visualforce page or from external code that assigns to a property.
Definition
Setter Methods in Salesforce Apex are methods on a controller class that receive values from user input on a Visualforce page or from external code that assigns to a property. They follow the naming convention set[PropertyName]() (set followed by the capitalized property name) and accept one parameter of the type the property holds. The platform invokes setters automatically as part of the Visualforce lifecycle: when a user submits a form on a Visualforce page, the platform deserializes the form fields into the corresponding controller properties by calling the setter for each.
Setters paired with getters (get[PropertyName] methods that return the property value) implement the JavaBean property pattern that Visualforce expects. Modern Apex also supports the shorter automatic property syntax (public String name with get and set blocks), which the compiler expands into equivalent getter and setter methods. Lightning Web Components do not use Apex setters in the same way; the framework relies on @api-decorated properties for parent-to-child data flow and on JavaScript setters for internal component state.
Setter Methods in Apex: convention, lifecycle, and modern alternatives
JavaBean property convention and Visualforce binding
Apex controllers expose properties to Visualforce pages through getter and setter methods. The convention is that a property named MyProperty has a getter named getMyProperty() that returns the value and a setter named setMyProperty(MyType value) that assigns the value. Visualforce expressions ({!myProperty}) call the getter; form fields bound to the property invoke the setter on form submission. The convention is identical to JavaBeans in Java, which is where Apex inherits it. Modern Apex shortens this through automatic property syntax: public String myProperty with get and set blocks compiles to the equivalent explicit getter and setter behind the scenes. Both styles work in Visualforce; the automatic syntax is more concise and is the recommended default for simple properties.
Setter invocation order in the Visualforce lifecycle
When a user submits a Visualforce form (POST request), the platform restores the controller object from view state, then calls the setter for each form field in the order the fields appear in the Visualforce markup. Setters fire before the action method, so the action method sees the user-provided values by the time it runs. The order matters: if Setter B depends on the value Setter A assigned, A must appear earlier in the markup than B, or the dependency does not work. This subtle ordering issue produces bugs that are hard to debug because the bug manifests only on certain form layouts. Document setter dependencies in the controller code when they exist.
Custom logic in setters and the property side-effect pattern
Setters are not just data assignment; they can run arbitrary Apex code. Adding logic to a setter is the standard way to react to user input on a Visualforce form. Common patterns: validate the incoming value and throw an exception if invalid, normalize the value (trim whitespace, lowercase email addresses), trigger downstream calculations (when SubTotal changes, recalculate Tax and Total), maintain referential integrity (when AccountId changes, clear ContactId because the old Contact no longer belongs to the new Account). Side effects in setters work but are easy to abuse; long expensive setters slow down every form submission. Mature controllers keep setter logic short and push expensive work to the action method.
Setter access modifiers and visibility
Apex supports three access modifiers on getters and setters: private (visible only within the class), public (visible within the namespace), and global (visible across namespaces, required for managed packages). The getter and setter can have different access modifiers in the automatic property syntax: public String myProp with public get and private set makes the property readable by external code but only settable by the class itself. This pattern is useful for properties that should be readable externally but only writable through controlled methods. For Visualforce-bound properties, both getter and setter need at least public access so the framework can call them.
Setters in modern Lightning Web Components vs Apex controllers
Lightning Web Components do not use Apex setter methods in the Visualforce-style binding pattern. LWC properties decorated with @api receive values from the parent component through the framework reactive update mechanism, not through Apex setters. JavaScript setters on LWC properties handle internal component state. The Apex controller behind an LWC typically exposes @AuraEnabled methods (instead of getters and setters) that the JavaScript calls explicitly. This architectural difference is one of several reasons LWC code looks quite different from Visualforce code. For controllers that back both Visualforce pages and LWCs, the same class often exposes both the JavaBean-style getters and setters for Visualforce and the @AuraEnabled methods for LWC; the two patterns coexist.
Testing setters in unit tests
Apex test methods can exercise setters directly without going through a Visualforce form submission. The test creates the controller instance, calls the setter with a sample value, and asserts the resulting state of the controller. This pattern verifies the setter validation, normalization, and side-effect logic without the overhead of a full Visualforce lifecycle. For setters with side effects on related records, the test should also assert the side effects: did the related record update as expected, did the calculated field reflect the new value. Setters paired with getters are covered together; the test calls the setter then calls the getter and confirms the round-trip preserves the value.
Writing effective setter methods in Apex
Writing effective setter methods in Apex is mostly about deciding when to use the automatic property syntax versus an explicit setter with custom logic. The four-step routine covers: pick the right syntax for the property, add validation and normalization logic where appropriate, document dependencies between setters, and test the setters explicitly in unit tests. Each step is a small decision; the cumulative effect on code quality is large. Mature Apex codebases keep setter logic short and predictable; long setters with side effects become maintenance debt quickly.
- Pick the right syntax for the property
For simple properties that just hold a value with no logic, use the automatic property syntax: public String myProperty with get and set blocks. The compiler generates the getter and setter. For properties that need validation, normalization, or side effects, write the explicit setter: public void setMyProperty(String value) with custom logic then assign this.myProperty equals value. The decision is per-property; some properties in the same class use automatic syntax while others use explicit setters. Document the rationale in a comment when explicit setters are used for non-obvious reasons; future maintainers may wonder why the property does not use the automatic syntax.
- Add validation and normalization logic where appropriate
For properties that need validation (the value must be in a specific range, the email must be properly formatted, the picklist value must match the allowed list), add explicit setter logic that checks the value and either throws an exception or rejects the assignment. For properties that need normalization (trim whitespace, lowercase, format as a phone number), add the normalization in the setter so every entry path through the property produces consistent data. Keep the validation and normalization logic short; long setter logic slows down every form submission and complicates testing.
- Document setter dependencies
When Setter B depends on the value Setter A assigned (a calculation, a related field update), the order in which the platform calls the setters matters. The platform calls setters in the order the corresponding fields appear in the Visualforce markup, so the dependency works as long as A field appears before B field on the page. Document this dependency in a comment on both setters so future maintainers do not move the fields around and break the calculation. For complex dependency chains, consider moving the dependent logic to the action method instead, where the order is explicit.
- Test setters explicitly in unit tests
Write Apex test methods that exercise the setters directly: create the controller instance, call the setter with sample values (valid, invalid, edge cases), and assert the resulting controller state. For setters with side effects on related records, also assert the side effects in the test. Mock external dependencies (HTTP callouts, custom settings) with the standard test mocking patterns. Aim for high test coverage on setter logic; setters are where most input-validation bugs hide, and good coverage catches them before they reach production. Add the setter tests to your CI pipeline so changes to setter logic get validated automatically.
- Setters fire in the order Visualforce fields appear in the markup. Dependencies between setters break if the fields are reordered; document the dependency explicitly in a comment.
- Long setter logic slows down every form submission. Keep validation and normalization short; push expensive work to the action method that fires after the setters.
- Automatic property syntax requires both get and set; you cannot write public String myProp with set only alone. Use the explicit setter syntax if you want a setter without a getter, which is rare.
- Lightning Web Components do not use Apex setters in the same Visualforce pattern. Controllers that back both LWC and Visualforce expose @AuraEnabled methods for LWC and JavaBean-style getters and setters for Visualforce.
- Setters with side effects on related records run during form submission. If the side effects depend on records that do not yet exist (a new record being created), the side effects fail; defer them to the action method.
Trust & references
Straight from the source - Salesforce's reference material on Setter Methods.
- Apex PropertiesSalesforce Developer Docs
- Visualforce Order of ExecutionSalesforce Developer Docs
- Apex Access ModifiersSalesforce Developer Docs
Hands-on resources to go deeper on Setter Methods.
About the Author
Dipojjal Chakrabarti is a B2C Solution Architect with 29 Salesforce certifications and over 13 years in the Salesforce ecosystem. He runs salesforcedictionary.com to help admins, developers, architects, and cert/interview candidates sharpen their fundamentals. More about Dipojjal.
Test your knowledge
Q1. What are Setter Methods?
Q2. What naming convention do they follow?
Q3. What's the modern equivalent?
Discussion
Loading discussion…