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.
ApexDoc Examples
See practical examples of ApexDoc comments applied to various Apex
constructs.
Class Example
1/**
2 * Manages customer account information and related operations.
3 * This class bypasses user record access via 'without sharing' so that it
4 * can be used in a batch classes.
5 * @author John Developer
6 * @since 0.1.0
7 * @version 0.3.1
8 * @see AccountProcessingBatch
9 * @group Account
10 * @example
11 * {@code
12 * Account a;
13 * try {
14 * a = new AccountManager().createAccount('Acme', 'Agriculture');
15 * } catch (AccountManager.AccountException caught) {
16 * LOGGER.log(caught);
17 * // further exception handling
18 * }
19 * }
20 */
21public without sharing class AccountManager {
22
23 /**
24 * The default region for new accounts if not specified.
25 */
26 public static final String DEFAULT_REGION = 'North America';
27
28 /**
29 * Stores the count of active accounts managed by this instance.
30 * Populated after using the {@link AccountService}.
31 */
32 @TestVisible
33 private Integer activeAccountCount;
34
35 /**
36 * Creates a new Account sObject with the given name and industry.
37 * @param accountName The desired name for the new account. Cannot be null or empty.
38 * @param industry The industry classification for the new account.
39 * @return The newly created Account sObject with its ID populated.
40 * @throws AccountManager.AccountException if accountName is invalid
41 * or if DML operation fails.
42 */
43 public Account createAccount(String accountName, String industry) {
44 if (String.isBlank(accountName)) {
45 throw new AccountManager.AccountException('Account name cannot be blank.');
46 }
47 Account acc = new Account(Name = accountName, Industry = industry);
48 // Potentially more logic here
49 try {
50 insert acc;
51 } catch (DmlException e) {
52 throw new AccountManager.AccountException(
53 'Failed to create account: ' + e.getMessage()
54 );
55 }
56 return acc;
57 }
58
59 // more methods...
60
61 /**
62 * Represents an exception specific to AccountManager operations.
63 * @example
64 * {@code
65 * throw new AccountManager.AccountException('Account not found with provided Id.');
66 * }
67 */
68 public class AccountException extends Exception {}
69}Packaged Class Example
1/**
2 * Provides services for geolocation and address conversion.
3 * @author Dennis Smith
4 * @version 0.3.0
5 * @since 0.1.0
6 */
7global with sharing class GeolocationService {
8 /**
9 * Represents geographic coordinates (latitude and longitude).
10 */
11 global class Coordinates {
12 @AuraEnabled
13 public Decimal latitude;
14 @AuraEnabled
15 public Decimal longitude;
16
17 global Coordinates(Decimal lat, Decimal lon) {
18 this.latitude = lat;
19 this.longitude = lon;
20 }
21 }
22
23 /**
24 * Converts a full address string to approximate latitude
25 * and longitude coordinates. This method is deprecated and should no
26 * longer be used due to its reliance on an older, less accurate geocoding
27 * service and simpler parsing logic. It may not handle all address formats
28 * correctly and has a lower success rate.
29 * @param fullAddress The complete address string
30 * (e.g., "123 Main St, Anytown, CA 90210, USA").
31 * @return A `Coordinates` object representing the approximate latitude and longitude.
32 * @throws DeprecatedMethodCalledException If this method is invoked,
33 * informing the user to migrate to the newer, more robust `geocodeAddress` method.
34 * @deprecated in 0.2.0. Use {@link #geocodeAddress(
35 * String street,
36 * String city,
37 * String state,
38 * String postalCode,
39 * String country)} instead.
40 * @since 0.1.0
41 */
42 @Deprecated
43 global static Coordinates convertAddressToCoordinates(String fullAddress) {
44 throw new DeprecatedMethodCalledException(
45 'The method `GeolocationService.convertAddressToCoordinates(String fullAddress)` is deprecated. ' +
46 'Please use `GeolocationService.geocodeAddress(String street, String city, String state, String postalCode, String country)` ' +
47 'for all new and existing address-to-coordinate conversions to ensure better accuracy and reliability.'
48 );
49 }
50
51 /**
52 * Geocodes a structured address into precise latitude and longitude coordinates
53 * using a robust external geocoding service.
54 * This method provides higher accuracy and better handling of diverse address formats.
55 * @param street The street address (e.g., "123 Main St").
56 * @param city The city (e.g., "Anytown").
57 * @param state The state or province abbreviation (e.g., "CA").
58 * @param postalCode The postal or ZIP code (e.g., "90210").
59 * @param country The country name or code (e.g., "USA").
60 * @return A Coordinates object containing the latitude and longitude.
61 * @throws GeocodingException If the address cannot be geocoded,
62 * if the external service is unavailable, or if required address
63 * components are missing.
64 * @example
65 * {@code
66 * try {
67 * GeolocationService.Coordinates coords = GeolocationService.geocodeAddress(
68 * '415 Mission St',
69 * 'San Francisco',
70 * 'CA',
71 * '94105',
72 * 'USA'
73 * );
74 * } catch (GeolocationService.GeocodingException e) {
75 * // handle failure
76 * }
77 * }
78 * @since 0.2.0
79 */
80 global static Coordinates geocodeAddress(
81 String street,
82 String city,
83 String state,
84 String postalCode,
85 String country
86 ) {
87 // Implement actual geocoding logic
88 return new Coordinates(0, 0);
89 }
90
91 /**
92 * Exception thrown when a deprecated method is called.
93 * This indicates that the caller should migrate to the recommended alternative.
94 */
95 global class DeprecatedMethodCalledException extends Exception {
96 }
97
98 /**
99 * Exception thrown when a geocoding operation fails.
100 * This provides specific context for issues during address-to-coordinate conversion.
101 */
102 global class GeocodingException extends Exception {
103 }
104}Test Class Example
1/**
2 * Specifications for the GeolocationService
3 * @author Jane Devington
4 * @version 0.2.0
5 * @see GeolocationService
6 * @since 0.1.0
7 */
8@IsTest
9private class GeolocationServiceTest {
10 /**
11 * Verifies that known addresses are correctly geocoded to their expected coordinates.
12 * @see GeolocationService#geocodeAddress(
13 * String street,
14 * String city,
15 * String state,
16 * String postalCode,
17 * String country)
18 */
19 @IsTest
20 private static void validAddressShouldReturnCorrectCoordinates() {
21 String street = '415 Mission Street';
22 String city = 'San Francisco';
23 String state = 'CA';
24 String postalCode = '94105';
25 String country = 'USA';
26
27 GeolocationService.Coordinates coords;
28 Test.startTest();
29 coords = GeolocationService.geocodeAddress(
30 street,
31 city,
32 state,
33 postalCode,
34 country
35 );
36 Test.stopTest();
37
38 Assert.isNotNull(
39 coords,
40 'Coordinates should not be null for a valid address.'
41 );
42 Assert.areEqual(
43 37.785834,
44 coords.latitude,
45 'Latitude should match for Salesforce tower.'
46 );
47 Assert.areEqual(
48 -122.406417,
49 coords.longitude,
50 'Longitude should match for Salesforce tower.'
51 );
52 }
53
54 /**
55 * Verifies that calling the geocodeAddress with missing required parameters
56 * throws a GeocodingException.
57 * @see GeolocationService#geocodeAddress(
58 * String street,
59 * String city,
60 * String state,
61 * String postalCode,
62 * String country)
63 * @see GeolocationService#GeocodingException
64 */
65 @IsTest
66 private static void missingRequiredParametersShouldThrowGeocodingException() {
67 String street = ''; // Missing
68 String city = 'San Francisco';
69 String state = 'CA';
70 String postalCode = 94105;
71 String country = 'USA';
72
73 Test.startTest();
74 Boolean caughtException = false;
75 try {
76 GeolocationService.geocodeAddress(
77 street,
78 city,
79 state,
80 postalCode,
81 country
82 );
83 } catch (GeolocationService.GeocodingException e) {
84 caughtException = true;
85 Assert.areEqual(
86 'Street, City, and Postal Code are required for geocoding.',
87 e.getMessage(),
88 'Exception message should indicate missing required fields.'
89 );
90 }
91 Test.stopTest();
92
93 Assert.isTrue(
94 caughtException,
95 'GeocodingException should have been thrown for missing street.'
96 );
97 }
98
99 /**
100 * Verifies that calling the deprecated method throws a
101 * DeprecatedMethodCalledException.
102 * @see GeolocationService#convertAddressToCoordinates(String address)
103 * @see GeolocationService#DeprecatedMethodCalledException
104 */
105 @IsTest
106 private static void deprecatedMethodCallShouldThrowDeprecatedMethodCalledException() {
107 String oldAddress = '123 Deprecated Lane';
108
109 Test.startTest();
110 Boolean caughtException = false;
111 try {
112 GeolocationService.convertAddressToCoordinates(
113 oldAddress
114 );
115 } catch (GeolocationService.DeprecatedMethodCalledException e) {
116 caughtException = true;
117 Assert.isTrue(
118 e.getMessage().contains('is deprecated'),
119 'Exception message should indicate deprecation.'
120 );
121 Assert.isTrue(
122 e.getMessage().contains('Please use'),
123 'Exception message should suggest new method.'
124 );
125 }
126 Test.stopTest();
127
128 Assert.isTrue(
129 caughtException,
130 'DeprecatedMethodCalledException should have been thrown.'
131 );
132 }
133}Interface Example
1/**
2 * Defines a contract for objects that can be serialized to a
3 * specific format. Implementations must provide logic for converting
4 * their state into a string representation.
5 * @author Jane Coder
6 * @since 0.2.0
7 */
8public interface ISerializable {
9 /**
10 * Serializes the object's current state into a String.
11 * @return A String representation of the object.
12 * @throws SerializationException if the object cannot be serialized.
13 */
14 String serialize();
15
16 /**
17 * Gets the format name this serializer supports (e.g., "JSON", "XML").
18 * @return The name of the serialization format.
19 */
20 String getFormatName();
21}Enum Example
1/**
2 * Represents the possible status levels for a support case.
3 * Defines standard values for case progression in the customer portal.
4 * @author John Developer
5 * @since 0.1.5
6 */
7public enum CaseStatus {
8 /* A newly opened case, not yet assigned. */
9 BRAND_NEW,
10 /* Case is actively being worked on. */
11 WORKING,
12 /* Case has been escalated to a higher tier. */
13 ESCALATED,
14 /* Case has been resolved and closed. */
15 CLOSED
16}Method Example (with params, return, throws)
1/**
2 * Calculates the total price for a list of products, applying a discount.
3 * @param productCodes A List of unique product codes to calculate the price for.
4 * Each code must correspond to an existing Product2 record.
5 * @param discountPercentage The discount percentage to apply (e.g., 10.5 for 10.5%).
6 * Must be between 0.0 and 100.0.
7 * @return The calculated total price as a Decimal after applying the discount.
8 * Returns 0.0 if productCodes is null or empty.
9 * @throws InvalidArgumentException if discountPercentage is out of range.
10 * @throws ProductNotFoundException if any productCode does not match an
11 * existing product.
12 */
13public Decimal calculateTotalPrice(
14 List<String> productCodes,
15 Decimal discountPercentage
16) {
17 if (discountPercentage < 0.0 || discountPercentage > 100.0) {
18 throw new IllegalArgumentException(
19 'Discount percentage must be between 0.0 and 100.0.'
20 );
21 }
22 if (productCodes == null || productCodes.isEmpty()) {
23 return 0.0;
24 }
25 //... implementation logic to fetch prices and calculate total...
26 return 100.0;
27}
28
29/**
30 * Represents an exception thrown when a requested product cannot be found.
31 * This custom exception provides a clear indication that a product lookup failed,
32 * allowing calling code to handle the 'not found' scenario specifically.
33 * It is typically thrown by methods attempting to retrieve Product2 records.
34 * @example
35 * {@code
36 * List<Product2> products = [
37 * SELECT Id
38 * FROM Product2
39 * WHERE ProductCode = :productCode
40 * LIMIT 1
41 * ];
42 * if (products.isEmpty()) {
43 * throw new ProductNotFoundException(
44 * 'Product with code ' + productCode + ' not found.'
45 * );
46 * }
47 * }
48 */
49public class ProductNotFoundException extends Exception {}Annotated Method (@AuraEnabled) Example
1public class OpportunityService {
2 /**
3 * Retrieves a list of open opportunities for a given account,
4 * accessible from Lightning Web Components. If the set of open opportunities
5 * can change during interaction with the component, the author will
6 * need to use {@code refreshApex()}.
7 * @param accountId The ID of the Account to retrieve opportunities for.
8 * @return A List of open Opportunity records. Returns an empty list if no
9 * open opportunities are found or if accountId is invalid.
10 * @see OpportunitySelector
11 */
12 @AuraEnabled(cacheable=true)
13 public static List<Opportunity> getOpenOpportunities(Id accountId) {
14 List<Opportunity> result = new List<Opportunity>();
15 //... implementation details...
16 return result;
17 }
18}External Reference Example
1/**
2 * Provides a service to retrieve current weather conditions from an external API.
3 * It utilizes Salesforce Named Credentials for secure endpoint and
4 * authentication management.
5 * @author John Doe
6 * @since 1.0.3
7 */
8public with sharing class WeatherService {
9 /**
10 * Retrieves the current weather conditions for a specified city and country.
11 * This method makes an HTTP GET callout to an external weather API using a
12 * Named Credential.
13 * @param city The name of the city (e.g., "London").
14 * @param country The name or code of the country (e.g., "UK" or "United Kingdom").
15 * @return A JSON string representing the current weather conditions.
16 * @throws WeatherServiceException If the HTTP callout fails, returns a non-200 status,
17 * or if there's an issue parsing the response.
18 * @see <a href="https://example.com/weather-api-docs/current-conditions.html">External
19 * Weather API</a>
20 */
21 public static String getCurrentWeather(
22 String city,
23 String country
24 ) {
25 if (String.isBlank(city) || String.isBlank(country)) {
26 throw new WeatherServiceException(
27 'City and country cannot be blank for weather lookup.'
28 );
29 }
30
31 String namedCredentialUrl = 'callout:WeatherAPI/current';
32 String requestParams =
33 '?city=' +
34 EncodingUtil.urlEncode(city, 'UTF-8') +
35 '&country=' +
36 EncodingUtil.urlEncode(country, 'UTF-8');
37
38 HttpRequest req = new HttpRequest();
39 req.setEndpoint(namedCredentialUrl + requestParams);
40 req.setMethod('GET');
41 req.setTimeout(60000);
42
43 Http http = new Http();
44 HttpResponse res;
45
46 try {
47 res = http.send(req);
48 } catch (System.CalloutException e) {
49 throw new WeatherServiceException(
50 'HTTP Callout Failed: ' + e.getMessage()
51 );
52 }
53
54 if (res.getStatusCode() == 200) {
55 return res.getBody();
56 } else {
57 throw new WeatherServiceException(
58 'Failed to retrieve weather data. Status: ' +
59 res.getStatusCode() +
60 '. Details: ' +
61 res.getBody()
62 );
63 }
64 }
65
66 /**
67 * Custom exception for errors during weather data retrieval.
68 */
69 public class WeatherServiceException extends Exception {
70 }
71}Inline Tags Example
1/**
2 * Sanitizes a given input string by removing or replacing certain
3 * characters such as {@code <script>}
4 * @param inputString The raw string provided by a user or external source.
5 * This string might contain malicious or unexpected characters,
6 * like a {@literal <script>} tag or a backslash {@literal \}.
7 * @return The sanitized string after processing.
8 * @example
9 * {@code
10 * String badInput = 'Hello, <script>alert(\'xss\')</script> World!';
11 * String safeOutput = SecurityUtils.sanitizeInput(badInput);
12 * System.debug('Sanitized Output: ' + safeOutput);
13 * } * @see {@link String#escapeHtml4} for a similar built-in method.
14 * {@hidden NOTE TO MAINTAINERS: This method should be updated if
15 * new security threats are identified. The current regex
16 * is designed to handle common XSS patterns but may not
17 * be exhaustive. The last major update was in v2.1.}
18 * @since 2.0
19 */
20global static String sanitizeInput(String inputString) {
21 // simple example for demonstration purposes
22 String sanitized = inputString;
23 sanitized = sanitized.replace('<script>', '').replace('</script>', '');
24 sanitized = sanitized.replace('(','(').replace(')',')');
25 return sanitized;
26}