Skip to content

AI-Powered Code Generation Best Practices — Write Code Faster with LLMs

DodaTech Updated 2026-06-22 9 min read

In this tutorial, you'll learn about AI. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Learn best practices for AI-powered Code Generation: craft effective prompts, review AI output safely, integrate LLMs into workflows, and avoid common pitfalls when using Copilot and ChatGPT.

What You'll Learn

You will learn how to generate high-quality code with AI assistants, write prompts that produce accurate results, review and test AI-generated code for security and correctness, and integrate LLMs into your development workflow without sacrificing code quality.

Why It Matters

AI Code Generation tools like GitHub Copilot, Claude, and ChatGPT can boost developer productivity by 30-55% on routine tasks. However, blindly accepting AI-generated code introduces security vulnerabilities, licensing issues, and logical errors. Knowing how to use these tools effectively separates productive developers from those who waste time fixing AI mistakes.

Real-World Use

The DodaZIP compression engine team uses AI-assisted Code Generation for boilerplate code, unit tests, documentation, and data processing scripts. Each AI-generated snippet goes through automated testing and manual review before merging. This workflow reduced development time for a new compression module by 40% while maintaining the same quality bar.

Your Learning Path

flowchart LR
  A[Infrastructure Automation] --> B[AI Code Generation]
  B --> C["CI/CD Pipelines"]
  C --> D[Production Deployment]
  B --> F{You Are Here}
  style F fill:#f90,color:#fff
â„šī¸ Info

Prerequisites: Proficiency in at least one programming language. Familiarity with Git workflows and automated testing. Understanding of basic application security concepts is recommended.

How AI Code Generation Works

Modern Code Generation models are large language models trained on billions of lines of public code. They predict the next tokens based on context -- your prompt, surrounding code, and comments.

Capabilities and Limitations

Capability Limitation
Generate boilerplate code May produce outdated or deprecated APIs
Write unit tests Tests may pass without actually verifying correctness
Explain complex code Explanations can be confidently wrong
Refactor functions May introduce subtle bugs in edge cases
Generate documentation Documentation may not match the actual implementation

Crafting Effective Prompts

The quality of AI-generated code depends directly on the quality of your prompt.

# Bad prompt (too vague):
"Write a function to parse CSV files."

# Good prompt (specific):
"Write a Python function that reads a CSV file path, handles
headers optionally, returns a list of dictionaries, supports
custom delimiters, and raises clear errors for missing files
or malformed rows. Include type hints and a docstring."
# AI response to the good prompt:
import csv
from typing import List, Dict, Optional, TextIO

def parse_csv(
    file_path: str,
    delimiter: str = ",",
    has_header: bool = True,
    encoding: str = "utf-8"
) -> List[Dict[str, str]]:
    """
    Parse a CSV file and return a list of dictionaries.

    Args:
        file_path: Path to the CSV file.
        delimiter: Field delimiter character.
        has_header: Whether the first row is a header.
        encoding: File encoding.

    Returns:
        List of dictionaries keyed by header or column index.

    Raises:
        FileNotFoundError: If the file does not exist.
        csv.Error: If the CSV is malformed.
    """
    try:
        with open(file_path, mode="r", encoding=encoding) as f:
            reader = csv.reader(f, delimiter=delimiter)
            rows = list(reader)
    except FileNotFoundError:
        raise FileNotFoundError(f"CSV file not found: {file_path}")
    except Exception as e:
        raise csv.Error(f"Failed to parse CSV: {e}")

    if not rows:
        return []

    if has_header:
        headers = rows[0]
        data_rows = rows[1:]
    else:
        headers = [str(i) for i in range(len(rows[0]))]
        data_rows = rows

    result = []
    for row in data_rows:
        if len(row) != len(headers):
            raise csv.Error(
                f"Row has {len(row)} fields, expected {len(headers)}"
            )
        result.append(dict(zip(headers, row)))

    return result

Expected behavior: The AI generates a complete, type-hinted function with error handling, docstring, and configurable parameters based on the detailed prompt.

Code Review Checklist for AI Output

Always review AI-generated code against this checklist:

## AI Code Review Checklist

- [ ] Does the code handle edge cases (empty input, None, zero)?
- [ ] Are there any hardcoded secrets, tokens, or credentials?
- [ ] Does the code use modern, non-deprecated APIs?
- [ ] Are imports necessary and correctly scoped?
- [ ] Are there any performance issues (N+1 queries, O(n^2) algorithms)?
- [ ] Does the code follow the project's style guide?
- [ ] Are there unit tests covering the new code?
- [ ] Is the license compatible with the project? (GPL, MIT, etc.)

Example: Spotting a Security Issue

# AI-generated code with a security vulnerability
from flask import Flask, request

app = Flask(__name__)

@app.route("/search")
def search():
    query = request.args.get("q")
    # VULNERABILITY: SQL injection
    results = execute_query(f"SELECT * FROM items WHERE name = '{query}'")
    return {"results": results}

Expected behavior: The AI-generated code is vulnerable to SQL Injection. The reviewer must flag this and request parameterized queries.

# Fixed version
@app.route("/search")
def search():
    query = request.args.get("q")
    # SAFE: parameterized query
    results = execute_query(
        "SELECT * FROM items WHERE name = %s",
        (query,)
    )
    return {"results": results}

AI-Assisted Test Generation

AI excels at generating unit tests, but you must verify they test the right things.

# Original function
def calculate_discount(price: float, customer_tier: str) -> float:
    """Calculate discount based on customer tier."""
    tiers = {
        "bronze": 0.05,
        "silver": 0.10,
        "gold": 0.15,
        "platinum": 0.20,
    }
    discount_rate = tiers.get(customer_tier, 0.0)
    return round(price * (1 - discount_rate), 2)

# AI-generated tests
import pytest

class TestCalculateDiscount:
    def test_bronze_tier(self):
        assert calculate_discount(100.0, "bronze") == 95.0

    def test_silver_tier(self):
        assert calculate_discount(100.0, "silver") == 90.0

    def test_gold_tier(self):
        assert calculate_discount(100.0, "gold") == 85.0

    def test_platinum_tier(self):
        assert calculate_discount(100.0, "platinum") == 80.0

    def test_unknown_tier_no_discount(self):
        assert calculate_discount(100.0, "guest") == 100.0

    def test_zero_price(self):
        assert calculate_discount(0.0, "gold") == 0.0

    def test_negative_price(self):
        assert calculate_discount(-50.0, "silver") == -45.0

    def test_rounding(self):
        assert calculate_discount(99.99, "gold") == 84.99

Expected behavior: AI generates comprehensive tests covering all tiers, edge cases, and rounding behavior. However, the reviewer should verify that the rounding test is correct (99.99 * 0.85 = 84.9915, rounded to 84.99 -- correct).

Integrating AI into Your Workflow

Inline Suggestions with GitHub Copilot

# Copilot can complete patterns as you type
def read_config(file_path: str) -> dict:
    """Read a YAML configuration file and return as dict."""
    import yaml
    # Start typing and Copilot suggests:
    try:
        with open(file_path, "r") as f:
            config = yaml.safe_load(f)
        return config or {}
    except FileNotFoundError:
        print(f"Config file not found: {file_path}")
        return {}
    except yaml.YAMLError as e:
        raise ValueError(f"Invalid YAML in {file_path}: {e}")

Expected behavior: As you type the function signature and docstring, Copilot suggests the implementation. You accept, review, and adjust as needed.

Chat-Based Code Generation

Prompt: "Generate a Python script that monitors a directory for new
files, calculates their SHA-256 hash, logs the results to a CSV file,
and moves the files to a processed folder. Include error handling for
file access issues and duplicate detection."

Expected behavior: The AI generates a complete script with file watching, hashing, CSV logging, error handling, and duplicate checking. You review each section before integrating.

Common AI Code Generation Mistakes

1. Trusting Output Without Review

AI models hallucinate. They generate plausible-looking code that may not compile, use non-existent APIs, or contain logical errors. Always compile, test, and review AI-generated code.

2. Providing Sensitive Context in Prompts

Pasting proprietary code, API keys, or internal logic into public AI tools exposes your intellectual property. Use enterprise-tier tools with data privacy guarantees or sanitize input before sharing.

3. Ignoring Licensing Issues

AI models trained on public code may reproduce GPL-licensed code verbatim. Using such code in a proprietary project creates legal risk. Run license checkers on AI-generated code.

4. Over-relying on AI for Complex Logic

AI performs well on common patterns and boilerplate but struggles with novel algorithms, domain-specific logic, and multi-step reasoning. Use AI for routine tasks, not critical architecture decisions.

5. Not Specifying the Language or Framework

A vague prompt like "write a sorting function" might generate Python, JavaScript, or Rust code depending on context. Always specify the language, framework, and version.

6. Accepting Inefficient Code

AI-generated code often favors readability over performance. Generated database queries may lack indexes, loops may be unnecessarily nested, and algorithms may be suboptimal. Profile and optimize where needed.

7. Skipping Tests for AI-Generated Code

AI-generated code needs the same (or more) testing as handwritten code. The AI does not know your specific requirements, edge cases, or business logic. Write tests before integrating.

Practice Questions

1. Why should you never paste proprietary code into a public AI chat tool? Public AI tools may use your input for model training or store it on their servers. Proprietary code could leak trade secrets. Use enterprise tools with data privacy guarantees or anonymize your code.

2. What is the most important step after generating code with AI? Review and test it. AI can produce code that looks correct but has logical errors, security vulnerabilities, or uses non-existent APIs. Never trust AI output without verification.

3. How can you improve the quality of AI-generated code? Write detailed prompts that specify the language, framework, expected inputs and outputs, error handling requirements, and coding conventions. Include examples of the desired output format.

4. What licensing risk does AI-generated code pose? AI models trained on public code repositories may reproduce code under copyleft licenses like GPL. Using this code in proprietary projects could create license Compliance obligations.

5. Challenge: Take a vague prompt like "write a file parser" and rewrite it as a detailed prompt that would produce production-quality code. Then compare the output from both prompts.

Mini Project: AI-Assisted Code Review Tool

Build a Python script that uses an AI API to review code snippets against a checklist of common issues (security, performance, style). The script should accept a file path, send the code to the AI with a structured prompt, and output a formatted review with recommendations.

import os
import sys
from openai import OpenAI

REVIEW_PROMPT = """Review the following code for:
1. Security vulnerabilities (injection, XSS, hardcoded secrets)
2. Performance issues (N+1 queries, inefficient loops)
3. Error handling (missing try-except, bare except)
4. Code style (naming conventions, dead code)
5. Edge cases (empty input, None, boundary values)

For each issue found, provide:
- Severity (critical, major, minor)
- Line number
- Description
- Suggested fix

Code to review:
```{language}
{code}

"""

def review_code(file_path): client = OpenAI() language = file_path.split(".")[-1] code = open(file_path).read()

response = client.chat.completions.create(
    model="gpt-4",
    messages=[{
        "role": "user",
        "content": REVIEW_PROMPT.format(
            language=language, code=code
        )
    }],
    temperature=0.1,
)

return response.choices[0].message.content

if name == "main": if len(sys.argv) < 2: print("Usage: python review.py <file_path>") sys.exit(1)

review = review_code(sys.argv[1])
print(review)

**Expected behavior:** The script reads a code file, sends it to the AI with a structured review prompt, and outputs a formatted review with severity levels, line numbers, and fix suggestions.

*Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.*

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro