1
---
2
name: salesforce-apex-quality
3
description: 'Apex code quality guardrails for Salesforce development. Enforces bulk-safety rules (no SOQL/DML in loops), sharing model requirements, CRUD/FLS security, SOQL injection prevention, PNB test coverage (Positive / Negative / Bulk), and modern Apex idioms. Use this skill when reviewing or generating Apex classes, trigger handlers, batch jobs, or test classes to catch governor limit risks, security gaps, and quality issues before deployment.'
4
---
5
6
# Salesforce Apex Quality Guardrails
7
8
Apply these checks to every Apex class, trigger, and test file you write or review.
9
10
## Step 1 — Governor Limit Safety Check
11
12
Scan for these patterns before declaring any Apex file acceptable:
13
14
### SOQL and DML in Loops — Automatic Fail
15
16
```apex
17
// ❌ NEVER — causes LimitException at scale
18
for (Account a : accounts) {
19
List<Contact> contacts = [SELECT Id FROM Contact WHERE AccountId = :a.Id]; // SOQL in loop
20
update a; // DML in loop
21
}
22
23
// ✅ ALWAYS — collect, then query/update once
24
Set<Id> accountIds = new Map<Id, Account>(accounts).keySet();
25
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
26
for (Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds]) {
27
if (!contactsByAccount.containsKey(c.AccountId)) {
28
contactsByAccount.put(c.AccountId, new List<Contact>());
29
}
30
contactsByAccount.get(c.AccountId).add(c);
31
}
32
update accounts; // DML once, outside the loop
33
```
34
35
Rule: if you see `[SELECT` or `Database.query`, `insert`, `update`, `delete`, `upsert`, `merge` inside a `for` loop body — stop and refactor before proceeding.
36
37
## Step 2 — Sharing Model Verification
38
39
Every class must declare its sharing intent explicitly. Undeclared sharing inherits from the caller — unpredictable behaviour.
40
41
| Declaration | When to use |
42
|---|---|
43
| `public with sharing class Foo` | Default for all service, handler, selector, and controller classes |
44
| `public without sharing class Foo` | Only when the class must run elevated (e.g. system-level logging, trigger bypass). Requires a code comment explaining why. |
45
| `public inherited sharing class Foo` | Framework entry points that should respect the caller's sharing context |
46
47
If a class does not have one of these three declarations, **add it before writing anything else**.
48
49
## Step 3 — CRUD / FLS Enforcement
50
51
Apex code that reads or writes records on behalf of a user must verify object and field access. The platform does **not** enforce FLS or CRUD automatically in Apex.
52
53
```apex
54
// Check before querying a field
55
if (!Schema.sObjectType.Contact.fields.Email.isAccessible()) {
56
throw new System.NoAccessException();
57
}
58
59
// Or use WITH USER_MODE in SOQL (API 56.0+)
60
List<Contact> contacts = [SELECT Id, Email FROM Contact WHERE AccountId = :accId WITH USER_MODE];
61
62
// Or use Database.query with AccessLevel
63
List<Contact> contacts = Database.query('SELECT Id, Email FROM Contact', AccessLevel.USER_MODE);
64
```
65
66
Rule: any Apex method callable from a UI component, REST endpoint, or `@InvocableMethod` **must** enforce CRUD/FLS. Internal service methods called only from trusted contexts may use `with sharing` instead.
67
68
## Step 4 — SOQL Injection Prevention
69
70
```apex
71
// ❌ NEVER — concatenates user input into SOQL string
72
String soql = 'SELECT Id FROM Account WHERE Name = \'' + userInput + '\'';
73
74
// ✅ ALWAYS — bind variable
75
String soql = [SELECT Id FROM Account WHERE Name = :userInput];
76
77
// ✅ For dynamic SOQL with user-controlled field names — validate against a whitelist
78
Set<String> allowedFields = new Set<String>{'Name', 'Industry', 'AnnualRevenue'};
79
if (!allowedFields.contains(userInput)) {
80
throw new IllegalArgumentException('Field not permitted: ' + userInput);
81
}
82
```
83
84
## Step 5 — Modern Apex Idioms
85
86
Prefer current language features (API 62.0 / Winter '25+):
87
88
| Old pattern | Modern replacement |
89
|---|---|
90
| `if (obj != null) { x = obj.Field__c; }` | `x = obj?.Field__c;` |
91
| `x = (y != null) ? y : defaultVal;` | `x = y ?? defaultVal;` |
92
| `System.assertEquals(expected, actual)` | `Assert.areEqual(expected, actual)` |
93
| `System.assert(condition)` | `Assert.isTrue(condition)` |
94
| `[SELECT ... WHERE ...]` with no sharing context | `[SELECT ... WHERE ... WITH USER_MODE]` |
95
96
## Step 6 — PNB Test Coverage Checklist
97
98
Every feature must be tested across all three paths. Missing any one of these is a quality failure:
99
100
### Positive Path
101
- Expected input → expected output.
102
- Assert the exact field values, record counts, or return values — not just that no exception was thrown.
103
104
### Negative Path
105
- Invalid input, null values, empty collections, and error conditions.
106
- Assert that exceptions are thrown with the correct type and message.
107
- Assert that no records were mutated when the operation should have failed cleanly.
108
109
### Bulk Path
110
- Insert/update/delete **200–251 records** in a single test transaction.
111
- Assert that all records processed correctly — no partial failures from governor limits.
112
- Use `Test.startTest()` / `Test.stopTest()` to isolate governor limit counters for async work.
113
114
### Test Class Rules
115
```apex
116
@isTest(SeeAllData=false) // Required — no exceptions without a documented reason
117
private class AccountServiceTest {
118
119
@TestSetup
120
static void makeData() {
121
// Create all test data here — use a factory if one exists in the project
122
}
123
124
@isTest
125
static void givenValidInput_whenProcessAccounts_thenFieldsUpdated() {
126
// Positive path
127
List<Account> accounts = [SELECT Id FROM Account LIMIT 10];
128
Test.startTest();
129
AccountService.processAccounts(accounts);
130
Test.stopTest();
131
// Assert meaningful outcomes — not just no exception
132
List<Account> updated = [SELECT Status__c FROM Account WHERE Id IN :accounts];
133
Assert.areEqual('Processed', updated[0].Status__c, 'Status should be Processed');
134
}
135
}
136
```
137
138
## Step 7 — Trigger Architecture Checklist
139
140
- [ ] One trigger per object. If a second trigger exists, consolidate into the handler.
141
- [ ] Trigger body contains only: context checks, handler invocation, and routing logic.
142
- [ ] No business logic, SOQL, or DML directly in the trigger body.
143
- [ ] If a trigger framework (Trigger Actions Framework, ff-apex-common, custom base class) is already in use — extend it. Do not create a parallel pattern.
144
- [ ] Handler class is `with sharing` unless the trigger requires elevated access.
145
146
## Quick Reference — Hardcoded Anti-Patterns Summary
147
148
| Pattern | Action |
149
|---|---|
150
| SOQL inside `for` loop | Refactor: query before the loop, operate on collections |
151
| DML inside `for` loop | Refactor: collect mutations, DML once after the loop |
152
| Class missing sharing declaration | Add `with sharing` (or document why `without sharing`) |
153
| `escape="false"` on user data (VF) | Remove — auto-escaping enforces XSS prevention |
154
| Empty `catch` block | Add logging and appropriate re-throw or error handling |
155
| String-concatenated SOQL with user input | Replace with bind variable or whitelist validation |
156
| Test with no assertion | Add a meaningful `Assert.*` call |
157
| `System.assert` / `System.assertEquals` style | Upgrade to `Assert.isTrue` / `Assert.areEqual` |
158
| Hardcoded record ID (`'001...'`) | Replace with queried or inserted test record ID |
159