1 min read

Clarify function contracts

Function contracts define how code components interact through inputs, outputs, and behaviors. They make code more predictable and testable by establishing clear agreements between different parts of a system. For AI systems, these contracts provide essential context for understanding code intent.

💡
Clear function contracts enable AI systems to better understand and generate code that maintains interface consistency without requiring comprehensive function analysis.

Example

/**
* Validates if a string is within 70 characters
* @throws {Error} If input is not a string
*/
function isValidLength(text: string): boolean {
  if (typeof text !== 'string') {
    throw new Error('Input must be string');
  }
  return text.length <= 70;
}

In this example, we use a combination of TypeScript types to define parameters and return types and JSDoc/TSDoc to define exceptions.

Recommendation

Use TypeScript types or JSDoc comments to define clear function contracts. Validate inputs/outputs explicitly and handle errors consistently. Choose descriptive parameter names that convey purpose and constraints.

Subscribe to our newsletter.

Be the first to know - subscribe today