AI-Assisted Software Development: A Comprehensive Guide with Practical Prompts (Part 2/3)
This is the second post in a series of three, each of which goes into great detail about how to properly integrate AI into your workflow when dealing with specific processes inherent to software development.
Here is an overview of this series:
- Part 1: Laying the Foundations — Project Planning, Design, and Architecture
- Part 2: Building with AI — Code Generation, Database Design, and Documentation
- Part 3: Polishing and Maintaining — Testing, Optimization, and Version Control
To make sure you don’t miss out on future posts, please be sure to follow.
Part 2: Building with AI — Code Generation, Database Design, and Documentation
Welcome to the second part of this series on AI-assisted software development. In this post, we’ll explore how AI can supercharge your coding process, help design efficient databases, and even assist in creating comprehensive documentation. I’ll provide practical prompts and techniques to make the most of AI in these crucial aspects of software development.
Mastering AI-Assisted Code Generation
So far, we’ve planned our project, designed our architecture. Now it’s time for the main event: actually writing some code!
Crafting Effective Prompts for Code Generation
English might be the best programming language to learn in the 21st century! The key to getting great code from your AI assistant is all in how you communicate your requests. I’ve learned (sometimes the hard way) that vague prompts lead to vague code. Here’s my go-to template for requesting code:
I need to implement [specific functionality] in [programming language].
Key requirements:
1. [Requirement 1]
2. [Requirement 2]
3. [Requirement 3]
Please consider:
- Error handling
- Edge cases
- Performance optimization
- Best practices for [language/framework]
Please do not unnecessarily remove any comments or code.
Generate the code with clear comments explaining the logic.
This structured approach helps the AI understand exactly what you need and consider important aspects that you might forget to mention explicitly.
Reviewing and Understanding AI-Generated Code
Now, here’s a crucial point: never, ever blindly copy-paste AI-generated code into your project. I made this mistake early on and spent hours debugging issues that I could have caught with a careful review.
When you receive code from the AI, follow these steps:
- Read through the entire code snippet: Get a general sense of the structure and approach.
- Check for logical errors: The AI might misunderstand a requirement or make incorrect assumptions.
- Look for best practices: Ensure the code follows conventions for your language and project.
- Verify error handling: Make sure edge cases and potential errors are handled appropriately.
- Understand every line: If there’s anything you don’t understand, ask the AI to explain it.
Here’s a prompt I use for getting explanations:
Can you explain the following part of the code in detail:
[paste code section]
Specifically:
1. What is the purpose of this section?
2. How does it work step-by-step?
3. Are there any potential issues or limitations with this approach?
Leveraging AI for Code Reviews and Improvements
One of my favorite uses of AI in coding is for code reviews. It’s like having a tireless senior developer looking over your shoulder, catching issues you might miss and suggesting improvements.
Try this prompt for code review:
Please review the following code:
[paste your code]
Consider:
1. Code quality and adherence to best practices
2. Potential bugs or edge cases
3. Performance optimizations
4. Readability and maintainability
5. Any security concerns
Suggest improvements and explain your reasoning for each suggestion.
I’ve found that AI often catches subtle issues that I’ve overlooked, especially when I’ve been staring at the code for too long.
Prompt Ideas for Various Coding Tasks
To help you get started with AI-assisted coding, here are some prompt ideas for common tasks:
- For implementing a specific algorithm:
Implement a [name of algorithm] in [programming language].
Please include:
1. The main function with clear parameter and return types
2. Helper functions if necessary
3. Time and space complexity analysis
4. Example usage
- For creating a class or module:
Create a [class/module] for [specific functionality] in [programming language].
Include:
1. Constructor/initialization
2. Main methods with clear docstrings
3. Any necessary private helper methods
4. Proper encapsulation and adherence to OOP principles
- For optimizing existing code:
Here's a piece of code that needs optimization:
[paste code]
Please suggest optimizations to improve its performance. For each suggestion, explain the expected improvement and any trade-offs.
- For writing unit tests:
Generate unit tests for the following function:
[paste function]
Include tests for:
1. Normal expected inputs
2. Edge cases
3. Invalid inputs
Use [preferred testing framework] syntax.
The AI Coding Workflow: A Step-by-Step Guide
Based on my experiences, here’s the workflow I’ve found most effective for AI-assisted coding:
- Start with a clear specification: Define what you want to build as clearly as possible.
- Generate initial code: Use a detailed prompt to get the AI to generate a first draft.
- Review and understand: Go through the code carefully, making sure you understand every part.
- Iterate and refine: Ask the AI for explanations, optimizations, and alternatives.
- Test and debug: Use AI to help generate unit tests and debug any issues.
- Optimize and refactor: Once the code is working, use AI to suggest optimizations and refactoring.
- Document: Use AI to help generate clear documentation for your code.
A Word of Caution: The Pitfalls of Over-Reliance
While AI is an incredibly powerful tool for coding, it’s crucial to maintain a healthy balance. Here are a few pitfalls I’ve encountered (and learned from):
- Losing sight of the big picture: Sometimes, in the back-and-forth with AI, it’s easy to lose sight of your overall architecture and design. Always keep your broader goals in mind.
- Accepting complex solutions for simple problems: AI might sometimes suggest overly complex solutions. Always strive for simplicity unless complexity is truly needed.
- Neglecting to learn the underlying concepts: It’s tempting to just use AI-generated code without fully understanding it. Resist this urge! Always take the time to learn and understand.
- Ignoring performance implications: AI might not always generate the most performant code out of the box. Always consider the performance implications, especially for critical parts of your system.
Database Design and Query Optimization with AI
Regardless of your experience with database design, AI can be a game-changer in this domain. AI can help us create robust database schemas and craft queries that would make even the most seasoned DBAs nod in approval.
Leveraging AI for Database Schemas
When it comes to designing database schemas, AI can be an invaluable brainstorming partner. Here’s a prompt I often use to get started:
I'm designing a database for [describe your application]. The main entities are:
[List main entities]
Key requirements:
1. [Requirement 1, e.g., "Must support fast retrieval of user posts"]
2. [Requirement 2, e.g., "Need to track user relationships (followers/following)"]
3. [Requirement 3, e.g., "Must handle large volumes of time-series data for analytics"]
Please suggest a database schema that includes:
1. Tables and their columns (with appropriate data types)
2. Primary and foreign key relationships
3. Any necessary junction tables for many-to-many relationships
4. Suggested indexes for performance
5. Considerations for scalability
Also, please explain the rationale behind your design choices.
This prompt ensures that the AI considers not just the basic structure, but also performance and scalability aspects.
Refining the Schema
Once you have an initial schema, it’s time to refine it. Here’s where AI can really shine by helping you think through different scenarios:
Given this initial schema:
[Paste your schema here]
Please analyze it considering the following:
1. Normalization: Is the schema properly normalized? If not, suggest improvements.
2. Denormalization: Are there any cases where denormalization might improve performance?
3. Indexing strategy: Suggest additional indexes that might improve query performance.
4. Scalability: How will this schema handle growth? Any potential bottlenecks?
5. Data integrity: Are there any constraints or triggers we should consider to ensure data consistency?
For each suggestion, please explain the pros and cons.
Crafting Optimized Queries
Now, let’s talk about query optimization. This is where I’ve found AI to be particularly helpful, especially for complex queries that make you question your life choices. Here’s a prompt I use for query optimization:
I need to optimize the following SQL query:
[Paste your query here]
The query is currently taking too long to execute on large datasets. Please:
1. Analyze the query and identify potential performance issues.
2. Suggest optimizations, which may include:
- Rewriting the query
- Adding or modifying indexes
- Suggestions for schema changes if necessary
3. Explain the reasoning behind each optimization.
4. If possible, provide an estimate of the performance improvement we might expect.
Additional context:
- Database system: [e.g., PostgreSQL, MySQL]
- Approximate table sizes: [e.g., Users table has 1 million rows]
- Any relevant hardware constraints
This prompt not only helps you optimize the specific query but also often provides insights that can be applied to other parts of your database interactions.
Prompt Ideas for Database-Related Tasks
To help you make the most of AI in your database work, here are some more specific prompt ideas:
- For index optimization:
Given the following table structure and common queries:
[Paste table structure and sample queries]
Please suggest an optimal indexing strategy. Consider:
1. Which columns should be indexed?
2. Should we use single-column or multi-column indexes?
3. Are there any cases where a covering index would be beneficial?
4. How might these indexes affect write performance?
- For data migration planning:
I need to migrate data from an old schema to a new one:
Old schema:
[Paste old schema]
New schema:
[Paste new schema]
Please help me create a migration plan:
1. Identify the steps needed to transform the data
2. Suggest any intermediate tables or views that might be helpful
3. Consider data integrity and how to handle potential conflicts
4. Propose a strategy to verify the migration's success
- For query performance troubleshooting:
The following query is performing poorly:
[Paste problematic query]
Execution plan:
[Paste execution plan if available]
Please analyze this query and suggest improvements:
1. Identify any sub-optimal parts of the query or execution plan
2. Suggest alternative ways to write the query
3. Are there any missing indexes that could help?
4. Would denormalizing any part of the schema improve performance for this query?
AI-Assisted Database Performance Tuning
One area where I’ve found AI to be incredibly helpful is in overall database performance tuning. Here’s a prompt I use for a general performance review:
I'm looking to improve the overall performance of my database. Here's an overview:
- Database system: [e.g., PostgreSQL 13]
- Current size: [e.g., 500GB]
- Main tables and their sizes: [List main tables]
- Common query patterns: [Describe typical queries]
- Current pain points: [e.g., slow joins on large tables, poor write performance during peak hours]
Please provide a comprehensive performance tuning plan, including:
1. Configuration parameters that might need adjustment
2. Indexing strategy review
3. Query optimization techniques
4. Potential schema optimizations
5. Caching strategies
6. Any other relevant suggestions for improving performance
For each suggestion, please explain the expected impact and any potential trade-offs.
This kind of comprehensive review can give you a solid roadmap for database optimization, often highlighting areas you might not have considered.
A Word of Caution: The Human Element in Database Design
While AI is an incredible tool for database work, it’s crucial to remember the importance of the human element:
- Business Logic Understanding: AI can suggest optimal structures, but you need to ensure they align with your specific business needs and future scalability requirements.
- Data Sensitivity: Be mindful of data privacy and security concerns that the AI might not be aware of in your specific context.
- Testing in Real-World Conditions: Always thoroughly test AI-suggested optimizations under conditions that mirror your production environment.
- Continuous Learning: Use AI as a learning tool. Don’t just implement its suggestions, but strive to understand the principles behind them.
- Regular Review: Database needs can change as your application evolves. Regularly review your database design and performance with AI assistance.
Documentation Made Easy
I know for many of us, writing docs feels like a chore but what if I told you that with AI, documentation can actually become an enjoyable and incredibly efficient part of your development process? Here are some tips on how you can use AI to transform the way you approach documentation.
Generating Documentation with AI
The key to great AI-generated documentation is, once again, in how you prompt the AI. Here’s a template I’ve found incredibly effective:
I need to create documentation for [project/component name]. Please generate:
1. An overview of the [project/component]
2. Installation instructions
3. Configuration options
4. API reference (if applicable)
5. Usage examples
6. Troubleshooting guide
7. FAQ section
For each section, consider:
- The target audience (e.g., developers, end-users)
- Any prerequisites or dependencies
- Common pitfalls or misconceptions
- Best practices
Please use clear, concise language and include relevant code snippets where appropriate.
This comprehensive prompt ensures that your AI assistant covers all the crucial aspects of good documentation.
Refining AI-Generated Docs for Accuracy and Clarity
Now, just like with code generation, you can’t just take the AI’s output and call it a day. Here’s my process for refining AI-generated documentation:
- Review for accuracy: Go through the docs and ensure all information aligns with your actual code and intended functionality.
- Check for clarity: Make sure explanations are clear and understandable to your target audience.
- Verify code snippets: Test any included code examples to ensure they work as expected.
- Add project-specific details: Incorporate any unique aspects of your project that the AI might not be aware of.
- Enhance with visuals: Consider where diagrams, flowcharts, or screenshots could enhance understanding.
Here’s a prompt I use for refining specific sections:
Please review and improve the following documentation section:
[Paste section here]
Consider:
1. Clarity of explanation
2. Completeness of information
3. Appropriate level of detail for the target audience
4. Consistency with best practices in technical writing
Suggest improvements and explain your reasoning.
Prompt Ideas for Different Types of Documentation
Different aspects of your project may require different approaches to documentation. Here are some prompts tailored for specific documentation needs:
- For API documentation:
Generate API documentation for the following endpoint:
[Paste endpoint details]
Include:
1. Endpoint URL and method
2. Request parameters and their types
3. Request body format (if applicable)
4. Response format and possible status codes
5. Example request and response
6. Any authentication requirements
7. Rate limiting information (if applicable)
- For a README file:
Create a README.md file for my GitHub repository. The project is [brief description]. Include:
1. Project title and description
2. Installation instructions
3. Usage examples
4. Contributing guidelines
5. License information
6. Badges (e.g., build status, version, etc.)
Use proper Markdown formatting and consider adding a table of contents for easier navigation.
- For user guides:
Generate a user guide for [product/feature name]. The target audience is [describe audience]. Include:
1. Introduction and purpose of the product/feature
2. Getting started guide
3. Main features and how to use them
4. Advanced usage tips
5. Troubleshooting common issues
Use simple language and consider including step-by-step instructions with hypothetical screenshots placeholders.
- For code comments and docstrings:
Generate appropriate comments and docstrings for the following code:
[Paste code here]
Follow [language-specific] conventions for docstrings. Include:
1. Brief description of the function/class
2. Parameters and their types
3. Return value and type
4. Any exceptions that might be raised
5. Usage examples if the function/class usage is not immediately obvious
Leveraging AI for Living Documentation
One of the coolest ways I’ve found to use AI in documentation is for maintaining “living documentation” — docs that evolve with your project. Here’s how I approach this:
- Version your documentation: Keep your docs in version control alongside your code.
- Update docs with code changes: Whenever you make significant code changes, use this prompt:
I've made the following changes to my code:
[Summarize changes]
Please update the relevant sections of the documentation to reflect these changes.
Highlight any breaking changes or new features that users should be aware of.
- Periodic review: Every few weeks or months, depending on your project pace, use this prompt:
Please review the following documentation:
[Paste current docs]
Considering the latest best practices and common user pain points in similar projects:
1. Suggest any sections that should be added or expanded
2. Identify any parts that might be outdated or no longer relevant
3. Recommend improvements for clarity and user-friendliness
This approach ensures your documentation stays up-to-date and continues to serve your users effectively.
The Hidden Benefits of AI-Assisted Documentation
Now, let me share something that really surprised me about using AI for documentation. I found that the process of creating and refining documentation with AI often led me to improve my actual code.
How? Well, in explaining concepts to the AI (and by extension, to my future users), I sometimes realized that certain parts of my code weren’t as intuitive or well-structured as I thought. This led me to refactor and improve the code itself.
Moreover, comprehensive documentation generated by AI sometimes helped me identify edge cases or potential features I hadn’t considered. It was like having a thorough, impartial reviewer for both my code and my thought process.
A Word of Caution: The Human Touch is Still Crucial
AI should not replace the need for human oversight and input. Here are a few things to keep in mind while writing documentation:
- Project-specific knowledge: AI can’t know the unique contexts or decisions behind your specific project. Make sure to inject this personal knowledge into your docs.
- User empathy: While AI can write clear instructions, you know your users best. Always review the docs from your users’ perspective.
- Branding and voice: If your project or company has a specific tone or style guide, you’ll need to adjust the AI-generated content accordingly.
- Sensitive information: Be careful not to include any sensitive or proprietary information in your prompts to the AI.
As we wrap up this section, I hope you’re seeing coding, design, and documentation in a new light. The tedious parts of software engineering don’t have to be a chore anymore. Using AI can become an integral part of your development process instead that improves both your code and your users’ experience.
The next post in this series will cover testing, optimisation, versioning, and not to mention, tons of prompt ideas!