kodelens
Back to Blog

Best Practices for Documenting Your Apex Code (That People Will Actually Read)

By Kodelens Team

October 20, 2025

Best Practices for Documenting Your Apex Code (That People Will Actually Read)

Code comments are like love letters to your future self.

You write them in a moment of perfect clarity, hoping to explain your brilliant, complex logic to the one person who will need it most: you, six months from now, at 4:45 PM on a Friday, with absolutely no memory of why you did what you did.

And yet, most of us don't write them. Why? Because we've all seen documentation that is either non-existent or, worse, actively unhelpful. It's often outdated, obvious, or fails to explain the one thing we actually need to know: why? As a result, developers stop writing it, and the vicious cycle continues.

The secret to good documentation isn't writing more of it; it's writing the right kind of it. This guide covers practical best practices for creating documentation that is genuinely useful, easy to maintain, and will actually be read.

The Golden Rule: Document the "Why," Not the "What"

This is the single most important principle. Your code should already explain what it is doing. Good documentation explains why it's doing it.

Consider this useless comment:

// Bad Comment: Explains the "what"
//
// Increment i
i++;

This adds zero value. It's just noise. Any competent developer can read the code and understand what it does.

Now consider this invaluable comment:

// Good Comment: Explains the "why"
//
// We must process this record in a future context to avoid a mixed DML error
// when a User is created in the same transaction as another sObject.
FutureHandler.process(recordId);

This is a perfect comment. It explains the hidden context: a specific Salesforce limitation (mixed DML error) and the business reason for the code's structure. It saves the next developer hours of frustrating research and debugging. Before you write a comment, ask yourself: "Am I explaining what the code does, or why it has to exist?"

Best Practice #1: The ApexDoc Header

The easiest way to bring professional-level documentation to your org is to adopt the ApexDoc standard. ApexDoc is a format for comments (similar to JavaDoc) that tools can use to automatically generate a documentation website for your entire codebase.

The Class Header: Every Apex class should start with a header that explains its overall purpose.

/**
 * @description Service class to handle all logic related to Opportunity line
 *              item calculations. Responsible for applying discounts, calculating
 *              taxes, and updating totals.
 * @author      Your Name
 * @date        2025-10-30
 */
public class OpportunityLineItemService { ... }

The Method Header: Every public method deserves a header explaining what it does, its parameters, and what it returns.

/**
 * @description Calculates the final, discounted price for a list of line items.
 * @param lineItems A List of OpportunityLineItems to be priced.
 * @return A Map of OpportunityLineItem IDs to their calculated final price.
 * @throws InvalidPriceException if a line item has a negative quantity.
 */
public Map<Id, Decimal> calculateFinalPrices(List<OpportunityLineItem> lineItems) { ... }

Best Practice #2: Inline Comments for "Weird" Code

Your code should strive to be clean and self-explanatory, but some things always require a little extra explanation. Use inline comments to shed light on the non-obvious parts of your code.

  • Complex Business Logic: // Per finance team requirements, VIP customers get an additional 5% discount.
  • Necessary Hacks or Workarounds: // HACK: Temp fix for API v2.1 bug that returns a null value. Should be removed after platform upgrade in Q1.
  • Platform-Specific Constraints: // Querying for the parent record here to avoid hitting a separate validation rule on the child.
  • "Magic Numbers" or Obscure Strings: if (status == 'A7') { // 'A7' is the legacy code for 'Pending Approval from Legal'

Best Practice #3: Let the Code Speak for Itself

Often, the urge to write a comment is a sign that the code itself could be clearer. The best documentation is clean, readable code.

  • Use Descriptive Names: Instead of process(rec), name your method calculateTaxForInvoice(invoice). Instead of List<SObject> l, name your list accountsToUpdate. Good naming makes the code read like prose.
  • Extract Complex Logic into a Method: If you find yourself writing a multi-line comment to explain a complex, 10-line block of code, that's a signal. Extract that block into a new private method with a descriptive name. The method name becomes the documentation.

Best Practice #4: The AI-Powered Assist

Even with good habits, going back to document a large, existing codebase is a daunting task that rarely gets prioritized. This is where modern AI tools can revolutionize the process.

What if you could auto-generate the starting point for your documentation?

This is where a tool like Kodelens comes in. A planned feature allows you to right-click a complex, undocumented method, and the local AI will generate a summary of what the code does in plain English. This summary can then be used as the basis for your ApexDoc header, turning a 10-minute writing task into a 10-second "review and edit" task. It lowers the barrier to getting started.

Conclusion: Documentation is a Feature

Good documentation isn't a chore you do after the real work is done; it's a feature of a professional and maintainable codebase. It reduces onboarding time, speeds up debugging, and makes your entire team more efficient.

Focus on the "why," not the "what." Use ApexDoc headers for your classes and methods. Explain the "weird" parts of your code with inline comments, and strive to write clean, self-documenting code in the first place.

Go back to a class you wrote last month. Can a new developer understand it without talking to you? If not, take five minutes to add an ApexDoc header and a few "why" comments. Your future self will thank you.