Platform apex generate

From forcedotcom/sf-skills · View interactive version

Platform apex generate is an AI agent skill from the GitHub repository forcedotcom/sf-skills. Primary Apex authoring skill for class generation, refactoring, and review. ALWAYS ACTIVATE when the user mentions Apex, .cls, triggers, or asks to create/refactor a class (service, selector, domain, batch, queueable, schedulable, invocable, DTO, utility, interface, abstract, exception, REST resourc

How to use this skill

Skill file

Generating Apex

Use this skill for production-grade Apex: new classes, selectors, services, async jobs,

invocable methods, and triggers; and for evidence-based review of existing .cls OR .trigger.

Required Inputs

Gather or infer before authoring:

Defaults unless specified:

If the user provides a clear, complete request, generate immediately without unnecessary back-and-forth.


Workflow

All steps are sequential. Do not skip, merge, or reorder. If blocked, stop and ask for missing context. If not applicable, mark N/A with a one-line justification in the report.

Phase 1 — Author

  1. Discover project conventions
  1. Choose the smallest correct pattern (see Type-Specific Guidance below)
  1. Review templates and assets
  1. Author with guardrails -- apply every rule in the Rules section below
  1. Generate test classes -- Load the skill platform-apex-test-generate to create {ClassName}Test.cls and {ClassName}Test.cls-meta.xml. Apex tests are required to deploy; never create or edit test files without loading it.

Phase 2 — Validate (required before reporting)

Steps 6 and 7 each require a tool invocation and produce output that must appear in the Step 8 report. Do not present the report until both have run and their output is captured.

  1. Run code analyzer
  1. Execute Apex tests

Phase 3 — Report

  1. Report -- use the output format at the bottom of this file.

Rules

Hard-Stop Constraints (Must Enforce)

If any constraint would be violated in generated code, stop and explain the problem before proceeding:

| 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 without sharing defaults and data exposure |

| 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 (List, Map, Set) rather than Java types | Prevent compile errors |

| Verify methods exist in Apex before use | Prevent reliance on non-existent APIs |

| Avoid System.debug() in main code paths | Debug statements evaluate even when loggign is not active and consume CPU. Use a logging framework if required on main code paths |

| Never use @future methods | Use Queueable with System.Finalizer; @future cannot chain, cannot be called from Batch, and cannot accept non-primitive types |

Bulkification & Governor Limits

SOQL Optimization

Caching

Security

Security Verification

Before finalizing, verify: CRUD/FLS enforced (SOQL + DML) · explicit sharing keyword on every class · no hardcoded secrets or Record IDs · PII excluded from logs and error messages · error messages sanitized for end users.

Error Handling

Null Safety

Constants & Literals

Naming Conventions

| Type | Pattern | Example |

|---|---|---|

| Service | {SObject}Service | AccountService |

| Selector | {SObject}Selector | AccountSelector |

| Domain | {SObject}Domain | OpportunityDomain |

| Batch | {Descriptive}Batch | AccountDeduplicationBatch |

| Queueable | {Descriptive}Queueable | ExternalSyncQueueable |

| Schedulable | {Descriptive}Schedulable | DailyCleanupSchedulable |

| DTO | {Descriptive}DTO | AccountMergeRequestDTO |

| Wrapper | {Descriptive}Wrapper | OpportunityLineWrapper |

| Utility | {Descriptive}Util | StringUtil |

| Interface | I{Descriptive} | INotificationService |

| Abstract | Abstract{Descriptive} | AbstractIntegrationService |

| Exception | {Descriptive}Exception | AccountServiceException |

| REST Resource | {SObject}RestResource | AccountRestResource |

| Trigger | {SObject}Trigger | AccountTrigger |

| Trigger Action | TA_{SObject}_{Action} | TA_Account_SetDefaults |

Additional naming rules:

ApexDoc

Class-level format:

/**
 * Provides services for geolocation and address conversion.
 */
public with sharing class GeolocationService { }

Method-level format:

/**
 * @param paramName Description of the parameter
 * @return Description of the return value
 * @example
 * List<Account> results = AccountService.deduplicateAccounts(accountIds);
 */

Code Structure & Architecture

| 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 |


Async Decision Matrix

| Scenario | Default | Key Traits |

|---|---|---|

| Standard async work | Queueable | Job ID, chaining, non-primitive types, configurable delay (up to 10 min via AsyncOptions), dedup signatures |

| Very large datasets | Batch Apex | Chunked processing, max 5 concurrent; use QueryLocator for large scopes |

| Modern batch alternative | CursorStep (Database.Cursor) | 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 (System.Finalizer) | Runs regardless of Queueable success/failure |

| Long-running callouts | Continuation | Up to 3 per transaction, 3 parallel |

| Delays > 10 minutes | System.scheduleBatch() | Schedule a Batch job at a specific future time |

| Legacy fire-and-forget | @future | Do not use in new code — see Hard-Stop Constraints; replace with Queueable + Finalizer |


Type-Specific Guidance

Service

Selector

Domain

Batch

Queueable

Schedulable

DTO / Wrapper

Utility

Interface

Abstract

Custom Exception

Trigger

Trigger Action (TAF)

Invocable Method (`@InvocableMethod`)

REST Resource (`@RestResource`)

`@AuraEnabled` Controller


Output Expectations

Deliverables per class:

Deliverables per trigger:

Meta XML template:

<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>{API_VERSION}</apiVersion>
    <status>Active</status>
</ApexClass>

Report in this order:

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 code analyzer output or state "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>

Cross-Skill Integration

| Need | Delegate to |

|---|---|

| Apex tests / fix failures | platform-apex-test-generate skill |

| 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) |


Troubleshooting Boundary

This skill handles production .cls/.trigger/.apex issues only: compile/parse failures, deployment dependency errors, runtime governor-limit failures. For test execution, assertions, coverage, or sf apex run test failures, delegate to platform-apex-test-generate.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.