Best practices for AI-assisted code generation based on Google GenAI guidelines
and industry standards for producing high-quality, maintainable code.
Code Clarity and Readability
Generate code that is self-documenting and easy to understand
Clear code reduces maintenance burden and improves team productivity
Use descriptive variable and function names
Keep functions focused on a single responsibility
Add comments for complex business logic
Follow consistent formatting and style conventions
Defensive Programming
Generate code that handles errors gracefully and validates inputs
Robust error handling prevents runtime failures and improves user experience
Validate all inputs at function boundaries
Use appropriate error handling mechanisms for the language
Provide meaningful error messages
Handle edge cases explicitly
Test-Driven Development
Generate comprehensive tests alongside implementation code
Tests ensure correctness and enable safe refactoring
Write tests for all public interfaces
Test both success and failure scenarios
Use meaningful test descriptions
Ensure tests are deterministic and isolated
Use clear, descriptive names that express intent
calculateTotalPrice(items: Item[])
isValidEmailAddress(email: string)
calc(x: any[])
check(s: string)
Keep functions small and focused on a single responsibility
Aim for functions under 20-30 lines
Extract complex logic into helper functions
Use pure functions when possible
Minimize side effects
Implement comprehensive error handling
Use Result types for operations that can fail
= { success: true; data: T } | { success: false; error: E };
function parseJson(json: string): Result {
try {
const data = JSON.parse(json) as T;
return { success: true, data };
} catch (error) {
return { success: false, error: error.message };
}
}
]]>
Provide clear documentation for public APIs
Document function parameters and return values
Explain complex algorithms or business logic
Provide usage examples for non-trivial functions
Document any side effects or preconditions
Validate and sanitize all user inputs
Prevents injection attacks and data corruption
Use type-safe validation libraries
Sanitize inputs before processing
Use parameterized queries for database operations
Escape output when rendering to prevent XSS
Follow principle of least privilege
Minimizes potential damage from security breaches
Grant minimal necessary permissions
Use role-based access control
Validate authorization at each access point
Log security-relevant events
Protect sensitive data
Prevents data breaches and maintains user privacy
Encrypt sensitive data at rest and in transit
Use secure random number generation
Implement proper session management
Avoid logging sensitive information
Choose appropriate algorithms and data structures
Understand time and space complexity
Use efficient data structures for the use case
Avoid premature optimization
Profile before optimizing
Manage resources efficiently
Close resources properly (files, connections, etc.)
Use connection pooling for database access
Implement proper caching strategies
Avoid memory leaks
Generating overly complex solutions
Complex code is harder to understand, test, and maintain
Start with simple solutions and refactor when complexity is justified
Ignoring existing codebase patterns
Inconsistent patterns make the codebase harder to navigate
Analyze existing code to understand and follow established patterns
Insufficient error handling
Unhandled errors lead to poor user experience and debugging difficulties
Implement comprehensive error handling for all failure modes
Missing or inadequate tests
Untested code is prone to bugs and difficult to refactor safely
Generate comprehensive test coverage alongside implementation
- Requirements are clearly understood
- Existing patterns and conventions are identified
- API design is planned and reviewed
- Testing strategy is defined
- Code follows established patterns
- Error handling is comprehensive
- Security considerations are addressed
- Performance implications are considered
- All tests pass
- Code is properly documented
- Security review is completed
- Performance requirements are met