Notes
Hard coding record IDs in Apex is generally discouraged as it makes the code less flexible and maintainable. Instead, it's better to use dynamic queries or other methods to retrieve the required record IDs. Here's an example that demonstrates how to avoid hard coding record IDs in Apex
// Bad Practice: Hard coding record ID
String accountId = '001XXXXXXXXXXXX';
// Good Practice: Querying for record ID dynamically
String accountId = [SELECT Id FROM Account WHERE Name = 'My Account'].Id;
Checking access before performing DML (Data Manipulation Language) statements is a good practice to ensure that the current user has the necessary permissions to modify the records. You can use the sObject
class's isAccessible()
method to verify access before executing DML operations.
// Check access before performing DML
Account acc = new Account();
acc.Name = 'New Account';
if (Account.SObjectType.isCreateable()) {
if (Schema.sObjectType.Account.fields.Name.isCreateable()) {
if (acc.sObjectType.getDescribe().isCreateable()) {
// Perform DML operation
insert acc;
System.debug('Account created successfully.');
} else {
System.debug('Current user does not have create access on Account object.');
}
} else {
System.debug('Current user does not have create access on Name field of Account object.');
}
} else {
System.debug('Current user does not have create access on Account object.');
}
When performing SOQL queries, it's important to follow security best practices by checking the user's access level to the queried records. One approach is to utilize the WITH SECURITY_ENFORCED clause in the SOQL query.
By adding the WITH SECURITY_ENFORCED clause to the query, Salesforce enforces record-level security, ensuring that only accessible records are returned. This clause helps in preventing unauthorized access to sensitive data.
List<Account> accountList = [SELECT Name, Rating, Type FROM Account WITH SECURITY_ENFORCED];
To ensure compliance with Salesforce's governor limits, it's essential to be mindful of the limits imposed and incorporate strategies to work within those boundaries. The Limits class provides various methods to check limits, and leveraging them in your code is recommended. One such approach is to limit the number of records retrieved in a SOQL query based on the available query rows.
Consider the following example that limits the records in a SOQL query based on the remaining query rows:
List<Account> accountList = [SELECT Name, Rating, Type FROM Account LIMIT :(Limits.getLimitQueryRows() - Limits.getQueryRows())];