Loading...
Loading...
Compare original and translation side by side
.cls.trigger.cls.triggerwith sharingpublicglobal@RestResource66.0with sharingpublic@RestResourceglobal66.0N/AN/Aassets/references/platform-apex-test-generate{ClassName}.cls{ClassName}.cls-meta.xmlplatform-apex-test-generate{ClassName}Test.cls{ClassName}Test.cls-meta.xmlplatform-apex-test-generateassets/references/platform-apex-test-generate{ClassName}.cls{ClassName}.cls-meta.xmlplatform-apex-test-generate{ClassName}Test.cls{ClassName}Test.cls-meta.xmlplatform-apex-test-generaterun_code_analyzer.clssev0sev1sev2sf code-analyzer run --target <target>run_code_analyzer=unavailable: <error>{ClassName}Testsf apex run testplatform-apex-test-generatetest_execution=unavailable: <error>.clsrun_code_analyzersev0sev1sev2sf code-analyzer run --target <target>run_code_analyzer=unavailable: <error>sf apex run test{ClassName}Testplatform-apex-test-generatetest_execution=unavailable: <error>Analyzerrun_code_analyzer=unavailable: <reason>Testingtest_execution=unavailable: <reason>Analyzerrun_code_analyzer=unavailable: <reason>Testingtest_execution=unavailable: <reason>| Constraint | Rationale |
|---|---|
| Place all SOQL outside loops | Avoid query governor limits (100 queries) |
| Place all DML outside loops | Avoid DML governor limits (150 statements) |
| Declare a sharing keyword on every class | Prevent unintended |
| Use Custom Metadata/Labels/describe calls instead of hardcoded IDs | Ensure portability across orgs |
| Always handle exceptions (log, rethrow, or recover) | Prevent silent failures |
| Use bind variables for all dynamic SOQL with user input | Prevent SOQL injection |
Use Apex-native collections ( | Prevent compile errors |
| Verify methods exist in Apex before use | Prevent reliance on non-existent APIs |
Avoid | Debug statements evaluate even when loggign is not active and consume CPU. Use a logging framework if required on main code paths |
Never use | Use Queueable with |
| 约束 | 理由 |
|---|---|
| 将所有SOQL置于循环外 | 避免查询Governor Limits(100次查询) |
| 将所有DML置于循环外 | 避免DML Governor Limits(150条语句) |
| 为每个类声明共享关键字 | 防止意外的 |
| 使用自定义元数据/标签/describe调用而非硬编码ID | 确保跨组织的可移植性 |
| 始终处理异常(记录、重新抛出或恢复) | 防止静默失败 |
| 对所有含用户输入的动态SOQL使用绑定变量 | 防止SOQL注入 |
使用Apex原生集合( | 防止编译错误 |
| 使用前验证方法在Apex中存在 | 防止依赖不存在的API |
避免在主代码路径中使用 | 即使未启用日志,调试语句也会执行并消耗CPU。如果主代码路径需要日志,使用日志框架 |
绝不使用 | 使用带 |
Database.update(records, false)SaveResultMap<Id, SObject>Map<Id, List<SObject>>Set<Id>Set.contains()List.contains()AggregateResultGROUP BYTrigger.oldMapLimits.getQueries()Limits.getDmlStatements()Limits.getCpuTime()Database.update(records, false)SaveResultMap<Id, SObject>Map<Id, List<SObject>Set<Id>Set.contains()List.contains()GROUP BYAggregateResultTrigger.oldMapLimits.getQueries()Limits.getDmlStatements()Limits.getCpuTime()WHEREIdNameOwnerIdExternalIdSELECT *LIMITORDER BY__mdt{CustomMdt__mdt}.getAll().values()getInstance()WHEREIdNameOwnerIdExternalIdSELECT *LIMITORDER BY__mdt{CustomMdt__mdt}.getAll().values()getInstance()Cache.OrgCache.Sessionprivate static MapCache.OrgCache.Sessionprivate static Mapwith sharingwithout sharinginherited sharingWITH USER_MODEAccessLevel.USER_MODEDatabaseSchema.describeAuraHandledException@AuraEnabledwithout sharingwithout sharingwith sharingwith sharingwithout sharinginherited sharingWITH USER_MODEDatabaseAccessLevel.USER_MODESchema.describe@AuraEnabledAuraHandledExceptionwithout sharingwithout sharingwith sharingExceptiontry/catchnew CustomException('message', cause)@AuraEnabledAuraHandledExceptionExceptionExceptiontry/catchnew CustomException('message', cause)@AuraEnabledAuraHandledExceptionExceptionreturnthrowrecord.addError()null?.map.get(key)containsKey??String.isBlank(value)value == null || value.trim().isEmpty()returnrecord.addError()null?.map.get(key)containsKey??String.isBlank(value)value == null || value.trim().isEmpty()UPPER_SNAKE_CASEprivate static finalLabel.''UPPER_SNAKE_CASEprivate static finalLabel.''| Type | Pattern | Example |
|---|---|---|
| Service | | |
| Selector | | |
| Domain | | |
| Batch | | |
| Queueable | | |
| Schedulable | | |
| DTO | | |
| Wrapper | | |
| Utility | | |
| Interface | | |
| Abstract | | |
| Exception | | |
| REST Resource | | |
| Trigger | | |
| Trigger Action | | |
PascalCasecamelCasegetcreateprocessvalidateishascancamelCaseaccountsrelatedContacts{value}By{key}accountsById{noun}IdsUPPER_SNAKE_CASEacctksrec| 类型 | 模式 | 示例 |
|---|---|---|
| Service | | |
| Selector | | |
| Domain | | |
| Batch | | |
| Queueable | | |
| Schedulable | | |
| DTO | | |
| Wrapper | | |
| Utility | | |
| Interface | | |
| Abstract | | |
| Exception | | |
| REST Resource | | |
| Trigger | | |
| Trigger Action | | |
PascalCasecamelCasegetcreateprocessvalidateishascancamelCaseaccountsrelatedContacts{value}By{key}accountsById{noun}IdsUPPER_SNAKE_CASEacctksrecpublicglobal@param@return@throws@example/**
* Provides services for geolocation and address conversion.
*/
public with sharing class GeolocationService { }/**
* @param paramName Description of the parameter
* @return Description of the return value
* @example
* List<Account> results = AccountService.deduplicateAccounts(accountIds);
*/publicglobal@param@return@throws@example/**
* Provides services for geolocation and address conversion.
*/
public with sharing class GeolocationService { }/**
* @param paramName Description of the parameter
* @return Description of the return value
* @example
* List<Account> results = AccountService.deduplicateAccounts(accountIds);
*/| Layer | Owns | Must NOT contain |
|---|---|---|
| Trigger | Event routing only | Business logic, orchestration |
| Handler/Service | Flow control, coordination | Inline SOQL/DML/HTTP/parsing |
| Domain | Business rules, validation | Queries, callouts, persistence details |
| Data/Integration | SOQL, DML, HTTP | Business decisions |
| 层 | 负责内容 | 不得包含 |
|---|---|---|
| Trigger | 仅事件路由 | 业务逻辑、编排 |
| Handler/Service | 流程控制、协调 | 内联SOQL/DML/HTTP/解析 |
| Domain | 业务规则、验证 | 查询、调用、持久化细节 |
| Data/Integration | SOQL、DML、HTTP | 业务决策 |
| Scenario | Default | Key Traits |
|---|---|---|
| Standard async work | Queueable | Job ID, chaining, non-primitive types, configurable delay (up to 10 min via |
| Very large datasets | Batch Apex | Chunked processing, max 5 concurrent; use |
| Modern batch alternative | CursorStep ( | 2000-record chunks, higher throughput, no 5-job limit |
| Recurring schedule | Scheduled Flow (preferred) or Schedulable | Schedulable has 100-job limit; use only when chaining to Batch or needing complex Apex logic |
| Post-job cleanup | Finalizer ( | Runs regardless of Queueable success/failure |
| Long-running callouts | Continuation | Up to 3 per transaction, 3 parallel |
| Delays > 10 minutes | | Schedule a Batch job at a specific future time |
| Legacy fire-and-forget | | Do not use in new code — see Hard-Stop Constraints; replace with Queueable + Finalizer |
| 场景 | 默认选择 | 关键特性 |
|---|---|---|
| 标准异步工作 | Queueable | 作业ID、链式调用、非原始类型、可配置延迟(通过 |
| 超大数据集 | Batch Apex | 分块处理,最多5个并发;对大型范围使用 |
| 现代批处理替代方案 | CursorStep ( | 2000记录块,更高吞吐量,无5作业限制 |
| 定期调度 | Scheduled Flow(优先)或Schedulable | Schedulable有100作业限制;仅在需要链式调用Batch或复杂Apex逻辑时使用 |
| 作业后清理 | Finalizer ( | 无论Queueable成功与否都会运行 |
| 长时间运行的调用 | Continuation | 每个事务最多3个,并行3个 |
| 延迟超过10分钟 | | 在特定未来时间调度Batch作业 |
| 遗留即发即弃 | | 新代码中禁止使用 — 见强制停止约束;替换为Queueable + Finalizer |
assets/service.clsreferences/AccountService.clswith sharingpublicstaticAccountServiceExceptionassets/service.clsreferences/AccountService.clswith sharingpublicstaticAccountServiceExceptionassets/selector.clsreferences/AccountSelector.clsinherited sharingList<SObject>Map<Id, SObject>WITH USER_MODEassets/selector.clsreferences/AccountSelector.clsinherited sharingList<SObject>Map<Id, SObject>WITH USER_MODEassets/domain.clswith sharingassets/domain.clswith sharingassets/batch.clsreferences/AccountDeduplicationBatch.clswith sharingDatabase.Batchable<SObject>Database.Statefulstart()execute()finish()QueryLocatorDatabase.SaveResultassets/batch.clsreferences/AccountDeduplicationBatch.clswith sharingDatabase.Batchable<SObject>Database.Statefulstart()execute()finish()QueryLocatorDatabase.SaveResultassets/queueable.clswith sharingQueueableDatabase.AllowsCalloutsFinalizerAsyncOptionsassets/queueable.clswith sharingQueueableDatabase.AllowsCalloutsFinalizerAsyncOptionsassets/schedulable.clswith sharingexecute()scheduleDaily()assets/schedulable.clswith sharingexecute()scheduleDaily()assets/dto.clsComparable@JsonAccessassets/dto.clsComparable@JsonAccessassets/utility.clspublic staticprivateassets/utility.clspublic staticprivateassets/interface.clsassets/interface.clsassets/abstract.clswith sharingvirtualprotected virtualprotected abstractassets/abstract.clswith sharingvirtualprotected virtualprotected abstractassets/exception.clsException()('msg')(cause)('msg', cause)assets/exception.clsException()('msg')(cause)('msg', cause)assets/trigger.clsnew MetadataTriggerHandler().run();assets/trigger.clsnew MetadataTriggerHandler().run();TriggerAction.{Context}Trigger_Action__mdtTA_{SObject}_{ActionName}TriggerAction.{Context}Trigger_Action__mdtTA_{SObject}_{ActionName}@InvocableMethod@InvocableMethodassets/invocable.clswith sharingRequestResponse@InvocableVariablepublic staticList<Request>List<Response>labeldescriptioncategorycallout=true@InvocableVariablelabeldescriptionrequired=true/false@InvocableVariableIdSObjectList<T>MapSetBlobList<Id>List<SObject>isSuccesserrorMessageerrorTypee.getTypeName()assets/invocable.clswith sharingRequestResponse@InvocableVariablepublic staticList<Request>List<Response>labeldescriptioncategorycallout=true@InvocableVariablelabeldescriptionrequired=true/false@InvocableVariableIdSObjectList<T>MapSetBlobList<Id>List<SObject>isSuccesserrorMessageerrorTypee.getTypeName()@RestResource@RestResourceassets/rest-resource.clsglobal with sharingglobal@RestResource(urlMapping='/{resource}/v1/*')200201400404422500500Pattern.matches('[a-zA-Z0-9]{15,18}', value)LIMITORDER BYpageSizeoffsetApiResponsesuccessmessagedatarecordsassets/rest-resource.clsglobal with sharingglobal@RestResource(urlMapping='/{resource}/v1/*')200201400404422500500Pattern.matches('[a-zA-Z0-9]{15,18}', value)LIMITORDER BYpageSizeoffsetApiResponsesuccessmessagedatarecords@AuraEnabled@AuraEnabledwith sharingWITH USER_MODE@AuraEnabled(cacheable=true)cacheableAuraHandledExceptionwith sharingWITH USER_MODE@AuraEnabled(cacheable=true)cacheableAuraHandledException{ClassName}.cls{ClassName}.cls-meta.xml66.0{ClassName}Test.clsplatform-apex-test-generate{ClassName}Test.cls-meta.xmlplatform-apex-test-generate{TriggerName}.trigger{TriggerName}.trigger-meta.xml66.0<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>{API_VERSION}</apiVersion>
<status>Active</status>
</ApexClass>Apex work: <summary>
Files: <paths>
Design: <pattern / framework choices>
Workflow: all steps completed (1-8); any N/A justified
Risks: <security, bulkification, async, dependency notes>
Analyzer: <REQUIRED -- paste actual run_code_analyzer output or state "run_code_analyzer=unavailable: <reason>">
Testing: <REQUIRED -- paste actual test execution results (pass/fail, coverage) or state "test_execution=unavailable: <reason>">
Deploy: <dry-run or next step>{ClassName}.cls{ClassName}.cls-meta.xml66.0{ClassName}Test.clsplatform-apex-test-generate{ClassName}Test.cls-meta.xmlplatform-apex-test-generate{TriggerName}.trigger{TriggerName}.trigger-meta.xml66.0<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>{API_VERSION}</apiVersion>
<status>Active</status>
</ApexClass>Apex work: <summary>
Files: <paths>
Design: <pattern / framework choices>
Workflow: all steps completed (1-8); any N/A justified
Risks: <security, bulkification, async, dependency notes>
Analyzer: <REQUIRED -- paste actual run_code_analyzer output or state "run_code_analyzer=unavailable: <reason>">
Testing: <REQUIRED -- paste actual test execution results (pass/fail, coverage) or state "test_execution=unavailable: <reason>">
Deploy: <dry-run or next step>| Need | Delegate to |
|---|---|
| Apex tests / fix failures | |
| Describe objects/fields | metadata skill (if available) |
| Deploy to org | deploy skill (if available) |
| Flow calling Apex | Flow skill (if available) |
| LWC calling Apex | LWC skill (if available) |
| 需求 | 委托给 |
|---|---|
| Apex测试 / 修复失败 | |
| 描述对象/字段 | 元数据技能(如可用) |
| 部署到组织 | 部署技能(如可用) |
| Flow调用Apex | Flow技能(如可用) |
| LWC调用Apex | LWC技能(如可用) |
.cls.trigger.apexsf apex run testplatform-apex-test-generate.cls.trigger.apexsf apex run testplatform-apex-test-generate