Documentation:
While we strive to write code that is clear and self-explanatory, we recognize the essential role of documentation in maintaining a healthy codebase. Documentation is not just about making complex logic understandable; it also serves as a guide for future developers, including ourselves, who may need to revisit code months or even years later.
When to Document
Documentation should accompany any function where the purpose or the logic isn't immediately obvious from the code itself. This includes:
Complex Logic: If a function handles multiple conditions, performs intricate calculations, or uses algorithms that aren't immediately clear from the code.
APIs and Libraries: Functions that are part of a public API or are meant to be used as a library by other projects should always be documented to describe their behavior, parameters, and return types.
Tricky Implementations: Sometimes, the most efficient way to solve a problem might not be the clearest. These cases should always be documented to explain the reasoning behind the chosen approach.
How to Document
A good piece of documentation typically includes (usually written in JSDoc or equivalent):
Description: A brief explanation of what the function does.
Parameters: A list of parameters, what they represent, and any special considerations about their values.
Return Value: What the function returns, if not obvious.
Side Effects: Any side effects the function might have (e.g., modifying a global state, triggering an event, etc.).
Example
Here’s an example of how to document a function effectively:
/**
* Calculates the monthly payment for a loan based on the interest rate, principal amount, and duration.
* This function uses the formula for calculating the annuity payment.
*
* @param {number} principal - The total amount of the loan.
* @param {number} annualRate - The annual interest rate of the loan in decimal form (e.g., 0.05 for 5%).
* @param {number} years - The duration of the loan in years.
* @return {number} The monthly payment amount.
*/
function calculateMonthlyPayment(principal, annualRate, years) {
const monthlyRate = annualRate / 12;
const payments = years * 12;
return principal * monthlyRate / (1 - (Math.pow(1 + monthlyRate, -payments)));
}
Backend
In backend we use swagger in addition to this, heres more information about it.