salesforce-apex-quality
它能做什么
这个工具可以帮助你确保为 Salesforce 平台编写的代码既安全又高效。它会检查那些容易引发性能或安全问题的常见错误,比如一次性执行过多数据库操作,或者没有检查用户是否有权访问某些数据。
适用场景
- ✓编写或审查 Salesforce 的 Apex 代码时。
- ✓想避免 Salesforce 治理限制(governor limit)错误时。
- ✓想确保代码遵守用户权限(安全性)时。
技能链接
https://github.com/github/awesome-copilot/blob/main/skills/salesforce-apex-quality/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“请审查这段 Apex 代码,确保它符合 Salesforce 在安全性和限制方面的最佳实践。”
每周 5 个新技能,1 分钟读完。
工作原理
这个工具会分析你的代码,查找已知会引发问题的写法。例如,它会检查你是否在循环中查询数据库或更新数据,这种做法效率低下,还可能导致系统崩溃。它还会检查代码是否按照当前运行用户的权限来执行。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Salesforce Apex Quality Guardrails
Apply these checks to every Apex class, trigger, and test file you write or review.
Step 1 — Governor Limit Safety Check
Scan for these patterns before declaring any Apex file acceptable:
SOQL and DML in Loops — Automatic Fail
// ❌ NEVER — causes LimitException at scale
for (Account a : accounts) {
List<Contact> contacts = [SELECT Id FROM Contact WHERE AccountId = :a.Id]; // SOQL in loop
update a; // DML in loop
}
// ✅ ALWAYS — collect, then query/update once
Set<Id> accountIds = new Map<Id, Account>(accounts).keySet();
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds]) {
if (!contactsByAccount.containsKey(c.AccountId)) {
contactsByAccount.put(c.AccountId, new List<Contact>());
}
contactsByAccount.get(c.AccountId).add(c);
}
update accounts; // DML once, outside the loop
Rule: if you see [SELECT or Database.query, insert, update, delete, upsert, merge inside a for loop body — stop and refactor before proceeding.
Step 2 — Sharing Model Verification
Every class must declare its sharing intent explicitly. Undeclared sharing inherits from the caller — unpredictable behaviour.
| Declaration | When to use |
|---|---|
public with sharing class Foo |
Default for all service, handler, selector, and controller classes |
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. |
public inherited sharing class Foo |
Framework entry points that should respect the caller's sharing context |
If a class does not have one of these three declarations, add it before writing anything else.
Step 3 — CRUD / FLS Enforcement
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.
// Check before querying a field
if (!Schema.sObjectType.Contact.fields.Email.isAccessible()) {
throw new System.NoAccessException();
}
// Or use WITH USER_MODE in SOQL (API 56.0+)
List<Contact> contacts = [SELECT Id, Email FROM Contact WHERE AccountId = :accId WITH USER_MODE];
// Or use Database.query with AccessLevel
List<Contact> contacts = Database.query('SELECT Id, Email FROM Contact', AccessLevel.USER_MODE);
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.
Step 4 — SOQL Injection Prevention
// ❌ NEVER — concatenates user input into SOQL string
String soql = 'SELECT Id FROM Account WHERE Name = \'' + userInput + '\'';
// ✅ ALWAYS — bind variable
String soql = [SELECT Id FROM Account WHERE Name = :userInput];
// ✅ For dynamic SOQL with user-controlled field names — validate against a whitelist
Set<String> allowedFields = new Set<String>{'Name', 'Industry', 'AnnualRevenue'};
if (!allowedFields.contains(userInput)) {
throw new IllegalArgumentException('Field not permitted: ' + userInput);
}
Step 5 — Modern Apex Idioms
Prefer current language features (API 62.0 / Winter '25+):
| Old pattern | Modern replacement |
|---|---|
if (obj != null) { x = obj.Field__c; } |
x = obj?.Field__c; |
x = (y != null) ? y : defaultVal; |
x = y ?? defaultVal; |
System.assertEquals(expected, actual) |
Assert.areEqual(expected, actual) |
System.assert(condition) |
Assert.isTrue(condition) |
[SELECT ... WHERE ...] with no sharing context |
[SELECT ... WHERE ... WITH USER_MODE] |
Step 6 — PNB Test Coverage Checklist
Every feature must be tested across all three paths. Missing any one of these is a quality failure:
Positive Path
- Expected input → expected output.
- Assert the exact field values, record counts, or return values — not just that no exception was thrown.
Negative Path
- Invalid input, null values, empty collections, and error conditions.
- Assert that exceptions are thrown with the correct type and message.
- Assert that no records were mutated when the operation should have failed cleanly.
Bulk Path
- Insert/update/delete 200–251 records in a single test transaction.
- Assert that all records processed correctly — no partial failures from governor limits.
…
常见问题
什么是“治理限制”(governor limits)?
这是 Salesforce 设定的规则,用来限制代码可以执行的处理量,以确保平台对所有用户都能顺畅运行。
什么是“循环中的 SOQL/DML”?
指在循环中反复执行数据库查询(SOQL)或写入操作(DML,例如 insert、update、delete)。这种做法会消耗大量资源,通常是不被允许的。
“CRUD/FLS 安全”是什么意思?
CRUD(创建、读取、更新、删除)指的是创建、读取、更新或删除记录的权限。FLS(字段级安全)指的是访问记录中特定字段的权限。代码必须检查用户是否拥有这些权限。
详情
作者的原始描述
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 ga
repo: github/awesome-copilot
热度
- GitHub 星标
- 40k
- 排名
- #7412
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …
同一仓库的更多技能
acquire-codebase-knowledge
40k帮你的智能体理解并编写现有代码项目的文档。它有助于新成员快速上手,或者快速了解项目架构。
acreadiness-assess
40k让你的智能体评估一个项目对 AI 的准备程度,并生成报告。它有助于了解项目在使用 AI 工具方面的准备情况。
acreadiness-generate-instructions
40k帮你的智能体根据评估结果编写 AI 工具的指令文件。它有助于改善 AI 与代码的交互方式,并弥补已发现的不足。
acreadiness-policy
40k让你的智能体协助制定或应用 AI 项目评估的政策。它有助于规范项目的评估方式,并确保合规。