Skip to Content
Course content

181: Scaladoc Best Practices

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I was reviewing some PRs for a teammate recently, and I noticed a pattern that drives me crazy. They were writing Scaladocs that basically just repeated the method signature in English. You know the type: def calculateTotal(amount: Double): Double documented as "Calculates the total of the amount". It's noise. It adds lines to the file without adding a single bit of actual information to the developer using the API.

Let's look at a real piece of code I'm working on for a payment gateway integration and walk through how I actually approach writing documentation that's worth reading.

The "It's Obvious" Fallacy

Here is my starting point. I've got a trait for a PaymentProcessor. At first glance, I might think the logic is so simple it doesn't need much explanation.

trait PaymentProcessor {
  def processPayment(amount: BigDecimal, currency: String, providerId: String): Either[PaymentError, TransactionId]
}

If I just run the Scaladoc tool on this, the generated HTML is empty. If a new dev joins the team, they have to guess: Does currency need to be ISO 4217? What happens if the providerId is invalid? Is this method idempotent? The code tells them what it takes, but not how to use it correctly. Let's try to fix it, but I'll start with the "bad" way first, just to show you what to avoid.

/**
 * Processes a payment.
 * 
 * @param amount The amount to process.
 * @param currency The currency to use.
 * @param providerId The ID of the provider.
 * @return An Either containing the error or the transaction ID.
 */
def processPayment(amount: BigDecimal, currency: String, providerId: String): Either[PaymentError, TransactionId]

I'm cringing just looking at that. I've added ten lines of text and told the reader absolutely nothing they couldn't have inferred from the types. This is "checkbox documentation"—done just to satisfy a linter or a manager.

Fighting the Urge to Parrot the Code

The trick is to document the contract, not the signature. I want to tell the caller about the constraints and the expectations. Let's adjust the documentation to actually provide value. I'll ask myself: "What would I need to know to call this without crashing the system?"

/**
 * Initiates a financial transfer via the specified provider.
 * 
 * This operation is synchronous and will block until the provider responds 
 * or the internal timeout of 30 seconds is reached.
 * 
 * @param amount Must be positive. Amounts less than or equal to zero will 
 *               trigger a [[PaymentError.InvalidAmount]].
 * @param currency A three-letter ISO 4217 currency code (e.g., "USD", "EUR").
 * @param providerId The unique identifier for the gateway; must be registered 
 *                   in the system configuration.
 * @return A [[TransactionId]] if successful, or a [[PaymentError]] explaining 
 *         why the payment failed.
 */
def processPayment(amount: BigDecimal, currency: String, providerId: String): Either[PaymentError, TransactionId]

Now we're talking. I've explained the timeout behavior, the specific format required for the currency, and the precondition for the amount. I also used [[...]]. That's a crucial Scaladoc feature—it creates a clickable link to the mentioned class or object in the generated docs, making it much easier for the user to navigate the API.

Handling Complexity and Edge Cases

But wait, there's more. What if this method has weird edge cases? For example, what happens if the network cuts out halfway through? Just putting that in a paragraph can get messy. This is where I use Markdown lists to make the documentation scannable.

I'll add a section explaining the failure modes. I prefer to keep the main description high-level and use a list for the specifics.

/**
 * Initiates a financial transfer via the specified provider.
 * 
 * This operation is synchronous and blocks until completion. Note that 
 * network failures during the request may leave the transaction in an 
 * "Unknown" state on the provider's end.
 * 
 * Possible outcomes:
 *  - Success: Returns [[TransactionId]].
 *  - Validation Failure: Returns [[PaymentError.InvalidAmount]] or [[PaymentError.InvalidCurrency]].
 *  - Provider Error: Returns [[PaymentError.GatewayTimeout]] if the provider is unreachable.
 * 
 * @param amount Must be positive.
 * @param currency A three-letter ISO 4217 currency code.
 * @param providerId The unique identifier for the gateway.
 * @return A result indicating success or a specific [[PaymentError]].
 */
def processPayment(amount: BigDecimal, currency: String, providerId: String): Either[PaymentError, TransactionId]

By structuring it this way, I'm not just describing the method; I'm providing a manual. When you're the one maintaining a library used by fifty other developers, this is the difference between a quiet Friday afternoon and a Friday afternoon spent answering the same five questions on Slack.

The Final Polish

One last tip: avoid using words like "This method..." or "This function...". The reader knows they are looking at a method. Start with a strong verb like "Initiates", "Calculates", or "Retrieves". It keeps the documentation punchy and professional.




📋 Practical Task

Refactoring the Inventory Management API

You have been handed a WarehouseManager trait that is technically functional but has terrible documentation. The current Scaladocs are redundant and provide no actual guidance on how to use the API safely.

Your Task: Rewrite the Scaladoc for the adjustStock method. You must:

  • Remove redundant "parrot" descriptions (e.g., "The quantity to adjust").
  • Document the specific constraint: quantity cannot be zero.
  • Document the behavior: If the resulting stock would be negative, the method should return a StockError.InsufficientFunds.
  • Use [[...]] links to reference the StockError and InventoryItem types.
  • Use a Markdown list to describe the possible return outcomes.
trait WarehouseManager {
  /**
   * Adjusts the stock.
   * 
   * @param itemId The ID of the item.
   * @param quantity The quantity to adjust.
   * @return An Either with an error or the updated item.
   */
  def adjustStock(itemId: String, quantity: Int): Either[StockError, InventoryItem]
}

sealed trait StockError
case object InsufficientFunds extends StockError
case object ItemNotFound extends StockError

case class InventoryItem(id: String, currentStock: Int)
Rating
0 0

There are no comments for now.

to be the first to leave a comment.