Maintainability prompts are specialised instructions for AI code generation that prioritize long-term code sustainability over immediate execution. This collection provides templates and patterns to guide AI tools in producing code that is readable, extensible, and easily maintained by human developers over time.
Core Principles
When crafting maintainability-focused prompts, ensure they embody these fundamental principles:
Clarity Over Cleverness: Prioritize straightforward, self-documenting code over complex optimisations
Modularity: Encourage proper separation of concerns and component isolation
Comprehensive Documentation: Request inline comments and documentation that explain "why" not just "what"
Consistent Patterns: Establish and enforce consistent coding patterns and naming conventions
Future-Proof Design: Consider extensibility and potential changes from the beginning
Prompt Templates
General Maintainability Template
SITUATION: [Describe the system, existing architecture, and context]
CHALLENGE: Create [describe component] that prioritizes maintainability and readability
AUDIENCE: Developers who will maintain this code in the future, including those who weren't involved in initial development
FORMAT:
- Use clear, descriptive naming conventions
- Include meaningful comments explaining the "why" behind complex logic
- Follow the principle of least surprise
- Implement appropriate error handling with informative messages
- Organize code with logical separation of concerns
FOUNDATIONS:
- Prioritize readability over clever optimizations
- Include comprehensive input validation
- Implement proper exception handling
- Use consistent patterns throughout
- Create modular components with clear responsibilities
- Include unit tests that document expected behavior
Refactoring for Maintainability Template
SITUATION: Working with the following code that needs to be refactored for improved maintainability:
[Insert existing code]
CHALLENGE: Refactor this code to improve readability, maintainability, and extensibility while preserving functionality
AUDIENCE: The development team who will maintain this code long-term
FORMAT:
- Follow clean code principles
- Use consistent naming conventions
- Extract complex logic into well-named helper functions
- Add appropriate documentation
- Preserve existing functionality exactly
FOUNDATIONS:
- Break down complex functions into smaller, focused ones
- Improve variable and function naming for clarity
- Add explanatory comments for non-obvious logic
- Implement proper error handling
- Address any potential edge cases
- Maintain or improve test coverage
Maintainable API Design Template
SITUATION: Designing a [type of API] that will be used by multiple teams and maintained for several years
CHALLENGE: Create an API design that prioritizes maintainability, backward compatibility, and clear developer experience
AUDIENCE: Both API consumers and future maintainers
FORMAT:
- Follow RESTful principles (or GraphQL conventions if applicable)
- Use consistent endpoint naming
- Include comprehensive documentation
- Implement proper versioning strategy
- Define clear request/response contracts
FOUNDATIONS:
- Design for backward compatibility
- Include proper error responses with meaningful codes
- Implement comprehensive input validation
- Consider future extensibility
- Document potential breaking changes and migration paths
- Include rate limiting and security considerations
Component-Specific Maintainability Prompts
Database Access Layer
SITUATION: Building a data access layer for [describe application] using [specify database/ORM]
CHALLENGE: Create a maintainable data access layer that abstracts database operations and can accommodate future changes
AUDIENCE: Developers who will need to modify the data model as requirements evolve
FORMAT:
- Implement repository pattern
- Use clear method naming that describes intent
- Include comprehensive error handling
- Provide transaction support
- Document query performance considerations
FOUNDATIONS:
- Abstract database-specific details behind interfaces
- Implement proper connection management
- Include proper logging without exposing sensitive data
- Add comments explaining complex queries
- Consider future data model evolution
- Include unit tests with mock database implementations
User Interface Components
SITUATION: Developing UI components for [describe application] using [specify framework]
CHALLENGE: Create maintainable UI components that can be easily understood, reused, and modified
AUDIENCE: Frontend developers who will extend or modify these components
FORMAT:
- Follow component composition best practices
- Use clear prop/parameter naming
- Include comprehensive prop validation
- Implement responsive design considerations
- Document component usage with examples
FOUNDATIONS:
- Separate business logic from presentation
- Implement proper state management
- Include accessibility considerations
- Create reusable, single-responsibility components
- Document component interdependencies
- Include tests for component behavior
Configuration Management
SITUATION: Designing configuration management for [describe system]
CHALLENGE: Create a maintainable configuration system that is flexible, documented, and easy to modify
AUDIENCE: System administrators and developers who will need to adjust configuration
FORMAT:
- Use a hierarchical configuration structure
- Include clear naming for configuration parameters
- Provide comprehensive documentation
- Implement validation for configuration values
- Support multiple environments
FOUNDATIONS:
- Include reasonable defaults for all settings
- Document each configuration option with purpose and valid values
- Implement secure handling of sensitive configuration
- Provide clear error messages for misconfiguration
- Consider backward compatibility for future changes
- Include logging of configuration at startup
Best Practices for Maintainability Prompts
Request Documentation
Always explicitly request documentation in your prompts:
Please include:
- Header comments explaining the component's purpose and usage
- Function/method documentation with parameters and return values
- Inline comments for complex logic or non-obvious decisions
- Usage examples where appropriate
- Known limitations or considerations for future improvements
Specify Code Organization
Be explicit about how code should be organized:
Please organize the code with:
- Logical file structure and module separation
- Clear class/component hierarchy
- Consistent import/dependency organization
- Separation of concerns (data access, business logic, presentation)
- Proper encapsulation of implementation details
Request Extensibility Considerations
Encourage thinking about future changes:
Please design with these future considerations in mind:
- How would additional [features/entities/operations] be added?
- What parts might need to change if [specific requirement] changes?
- How can we minimize the impact of such changes?
- What extension points should be provided?
Error Handling Requirements
Specify expectations for error handling:
For error handling, please include:
- Validation of all inputs with informative error messages
- Graceful handling of external service failures
- Proper exception hierarchy and error codes
- Helpful error messages that guide toward resolution
- Logging that provides context without exposing sensitive data
Evaluating Results
When evaluating AI-generated code for maintainability, consider these questions:
Readability: Can developers quickly understand what the code does and why?
Modularity: Is the code properly separated into cohesive, loosely-coupled components?
Documentation: Is the code well-documented with meaningful comments?
Testability: Is the code structured in a way that makes it easy to test?
Extensibility: How easily can the code be extended or modified for future requirements?
Consistency: Does the code follow consistent patterns and naming conventions?
Error Handling: Does the code properly handle errors and edge cases?
Example: Before and After
Before: Function Without Maintainability Focus
function p(d, o) {
let r = [];
for(let i=0; i<d.length; i++) {
if(d[i].t === o.t) {
r.push(d[i]);
}
}
return r;
}
After: Function With Maintainability Focus
/**
* Filters data items by a specific type
* @param {Array} dataItems - The collection of data items to filter
* @param {Object} options - Filtering options
* @param {string} options.type - The type to filter by
* @returns {Array} - Data items matching the specified type
*/
function filterDataItemsByType(dataItems, options) {
// Validate inputs to prevent runtime errors
if (!Array.isArray(dataItems)) {
throw new Error('dataItems must be an array');
}
if (!options || typeof options.type === 'undefined') {
throw new Error('options.type must be specified');
}
// Return items that match the specified type
return dataItems.filter(item => item.type === options.type);
}
Maintainability Anti-Patterns to Avoid
When reviewing AI-generated code, watch for these common maintainability issues:
Magic Numbers/Strings: Unexplained literals embedded in code
Excessive Comments: Obvious comments that just repeat what the code does
Giant Functions: Long methods or functions that do multiple things
Deeply Nested Logic: Multiple levels of nested conditionals or loops
Duplicated Code: Similar code repeated in multiple places
Poor Naming: Cryptic variable or function names that don't convey purpose
Tight Coupling: Components that are highly dependent on implementation details of other components
Include specific requirements to avoid these in your prompts.
Conclusion
Maintainability-focused prompts create code that stands the test of time. By explicitly guiding AI tools to prioritize readability, documentation, and extensibility, you can generate code that not only works today but remains maintainable as requirements evolve and team members change.
Remember that truly maintainable code considers both the immediate needs and the future changes that will inevitably come. By investing in maintainability from the start through well-crafted prompts, you reduce technical debt and create a more sustainable codebase.