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に貼り付けるだけ。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 in loops」とは何ですか?
ループの中で、データベースへの問い合わせ(SOQL)や書き込み操作(insert、update、delete などの DML)を繰り返し行うことです。多くのリソースを消費するため、一般的に禁止されています。
「CRUD/FLS security」とは何ですか?
CRUD(Create、Read、Update、Delete)は、レコードを作成、参照、更新、削除する権限に関するものです。FLS(Field-Level Security)は、レコード内の特定のフィールドにアクセスする権限に関するものです。コードでは、ユーザーがこれらの権限を持っているかを確認する必要があります。
詳細
作者による元の説明
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プロジェクトの評価ポリシーの策定や適用を支援できるようにします。プロジェクトの評価方法を標準化し、コンプライアンスを確保するのに役立ちます。
似ているスキル
api-connector-builder
280kエージェントが既存のパターンに従って、新しいAPI連携を構築します。新しい方式を作らずに、もう一つ連携を追加したいときに使います。
api-design
280kエージェントがベストプラクティスに沿ってREST APIを設計できるようにします。APIの通信方法、エラーの表示方法、データの整理方法を決めるのに役立ちます。
backend-patterns
280kエージェントのサーバーサイドのアーキテクチャパターンとデータベースの最適化を支援します。サーバー上で動くコードを作成またはレビューするときに役立ちます。