This page contains intentional code issues commonly found in AI-generated code for testing and educational purposes. These examples demonstrate problems like hallucinated APIs, outdated patterns, security vulnerabilities, and incomplete implementations. Always review and test AI-generated code thoroughly before using it in production.
Common AI-Generated Code Issues
The following examples demonstrate problems frequently found in AI-generated code:
1. Hallucinated APIs and Methods Hallucination
AI often invents APIs, methods, or libraries that don't exist:
// VIOLATION: These methods don't exist
const data = await fetchData.sync('https://api.example.com');
const result = data.parseJSON(); // parseJSON doesn't exist
const user = User.getById(123); // User class doesn't exist
const response = http.get('https://api.example.com'); // http.get doesn't exist
2. Outdated or Deprecated Patterns Deprecated
AI may suggest old patterns that are no longer recommended:
// VIOLATION: Using deprecated patterns
var xhr = new XMLHttpRequest(); // Modern: use fetch()
xhr.open('GET', '/api/data', false); // Synchronous is deprecated
xhr.send();
// Using jQuery when not needed
$('#element').click(function() { ... }); // Modern: use addEventListener
// Old callback patterns
function getData(callback) {
setTimeout(function() {
callback(data);
}, 1000);
}
3. Missing Error Handling Incomplete
AI-generated code often lacks proper error handling:
// VIOLATION: No error handling
async function fetchUserData(userId) {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json(); // What if response fails?
return data.user.name; // What if user doesn't exist?
}
// No try-catch, no validation
function processPayment(amount) {
const result = paymentAPI.charge(amount); // What if API fails?
return result.success;
}
4. Security Vulnerabilities Security
AI may generate code with security issues:
// VIOLATION: SQL Injection vulnerability
function getUser(username) {
const query = `SELECT * FROM users WHERE username = '${username}'`;
return database.execute(query); // Vulnerable to SQL injection
}
// VIOLATION: XSS vulnerability
function displayComment(comment) {
document.getElementById('comments').innerHTML = comment; // No sanitization
}
// VIOLATION: Exposed credentials
const API_KEY = "sk_live_1234567890abcdef"; // Hardcoded in client
5. Incomplete Implementations Incomplete
AI may generate code that looks complete but is missing critical parts:
// VIOLATION: Missing implementation
function authenticateUser(username, password) {
// TODO: Implement authentication
return true; // Always returns true!
}
function validateEmail(email) {
// Check if email is valid
return email.includes('@'); // Too simple, missing proper validation
}
function calculateTotal(items) {
let total = 0;
// Missing: tax calculation, discount application, etc.
return total;
}
6. Overly Complex Solutions Complexity
AI sometimes generates unnecessarily complex code:
// VIOLATION: Overly complex for simple task
function getFirstItem(array) {
return array.reduce((accumulator, currentValue, currentIndex, sourceArray) => {
if (currentIndex === 0) {
return currentValue;
}
return accumulator;
}, undefined);
}
// Simple solution: return array[0];
// Unnecessary use of design patterns
class SingletonFactoryBuilder {
static getInstance() {
if (!this.instance) {
this.instance = new this();
}
return this.instance;
}
create() { return {}; }
}
// For a simple object creation
7. Incorrect Assumptions Assumption
AI may make incorrect assumptions about data structures or behavior:
// VIOLATION: Assumes data structure
function getUserName(user) {
return user.name.first + ' ' + user.name.last; // Assumes nested structure
}
// Assumes API response format
function processResponse(response) {
return response.data.results.items[0].value; // May not exist
}
// Assumes synchronous behavior
function saveData(data) {
localStorage.setItem('data', JSON.stringify(data));
return true; // Assumes it always succeeds
}
8. Missing Dependencies or Imports Missing
AI may use libraries without importing them:
// VIOLATION: Using libraries without imports
const data = axios.get('/api/data'); // axios not imported
const moment = moment().format('YYYY-MM-DD'); // moment not imported
const _ = _.map(array, fn); // lodash not imported
// Missing React imports
function MyComponent() {
return React.createElement('div', null, 'Hello'); // React not imported
}
9. Copy-Paste Errors Copy-Paste
AI may copy code with errors or incomplete modifications:
// VIOLATION: Copy-paste errors
function getUser(id) {
// Copied from getProduct, forgot to change variable names
const product = database.getProduct(id); // Should be getUser
return product.name; // Should be user.name
}
// Incomplete variable renaming
function calculateTotal(items) {
let sum = 0;
for (let item of products) { // Should be 'items'
sum += item.price;
}
return sum;
}
10. Inefficient or Anti-Pattern Code Performance
AI may generate inefficient code or anti-patterns:
// VIOLATION: Inefficient nested loops
function findDuplicates(array1, array2) {
const duplicates = [];
for (let i = 0; i < array1.length; i++) {
for (let j = 0; j < array2.length; j++) {
if (array1[i] === array2[j]) {
duplicates.push(array1[i]);
}
}
}
return duplicates; // O(n*m) complexity
}
// Anti-pattern: Modifying array while iterating
function removeItems(array) {
for (let i = 0; i < array.length; i++) {
if (array[i].shouldRemove) {
array.splice(i, 1); // Modifies array during iteration
}
}
}
11. Wrong Language Syntax Syntax
AI may mix syntax from different languages or versions:
// VIOLATION: Mixing Python and JavaScript
function getItems() {
items = [] // Python syntax (no let/const)
for item in items: // Python for loop
print(item) // Python print
}
// Wrong async/await usage
async function getData() {
return await Promise.resolve(data); // Unnecessary await
}
// Mixing old and new syntax
const obj = {
method: function() { ... }, // Old syntax
arrow: () => { ... } // New syntax, inconsistent
}
12. Missing Type Safety Type Safety
AI may generate code without proper type checking:
// VIOLATION: No type checking
function addNumbers(a, b) {
return a + b; // Works with strings too (unintended)
}
function processUser(user) {
return user.name.toUpperCase(); // What if user is null?
}
// TypeScript without proper types
function getData(id: any): any { // Using 'any' defeats purpose
return database.get(id);
}
13. Hardcoded Values Hardcoded
AI often includes hardcoded values that should be configurable:
// VIOLATION: Hardcoded values
function connectToDatabase() {
return new Database({
host: 'localhost',
port: 5432,
username: 'admin',
password: 'password123'
});
}
function getApiUrl() {
return 'https://api.example.com/v1'; // Should be from config
}
const MAX_RETRIES = 3; // Should be configurable
14. Missing Comments or Documentation Documentation
AI-generated code may lack proper documentation:
// VIOLATION: No documentation
function processData(data, options) {
const result = [];
for (let i = 0; i < data.length; i++) {
if (options.filter) {
result.push(data[i]);
}
}
return result;
}
// What does this function do? What are the parameters?
// What does options.filter mean?
15. Race Conditions and Async Issues Async
AI may generate code with race conditions or async bugs:
// VIOLATION: Race condition
let userData = null;
async function loadUser(id) {
fetch(`/api/users/${id}`).then(r => r.json()).then(d => {
userData = d; // May be overwritten by concurrent calls
});
}
// Missing await
async function saveData() {
const result = fetch('/api/save', {...}); // Missing await
return result; // Returns promise, not result
}
// Promise chain without error handling
function getData() {
return fetch('/api/data')
.then(r => r.json())
.then(d => d.items)
.then(i => i.map(x => x.value)); // No catch block
}
Good Code Examples
The following examples demonstrate proper coding practices:
1. Using Real APIs and Methods Correct
// Compliant: Using real APIs
async function fetchUserData(userId) {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
}
2. Modern Patterns and Best Practices Modern
// Compliant: Modern async/await
async function getData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
// Modern event handling
document.getElementById('button').addEventListener('click', handleClick);
3. Proper Error Handling Error Handling
// Compliant: Comprehensive error handling
async function fetchUserData(userId) {
try {
if (!userId || typeof userId !== 'number') {
throw new Error('Invalid user ID');
}
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`Failed to fetch user: ${response.statusText}`);
}
const data = await response.json();
if (!data || !data.user) {
throw new Error('Invalid response format');
}
return data.user;
} catch (error) {
console.error('Error in fetchUserData:', error);
// Handle error appropriately (show user message, retry, etc.)
throw error;
}
}
4. Secure Code Secure
// Compliant: Parameterized queries
async function getUser(username) {
const query = 'SELECT * FROM users WHERE username = ?';
return database.execute(query, [username]); // Prevents SQL injection
}
// Compliant: XSS prevention
function displayComment(comment) {
const element = document.getElementById('comments');
element.textContent = comment; // textContent escapes HTML
// Or use proper sanitization library
}
// Compliant: Environment variables
const API_KEY = process.env.API_KEY; // Server-side only
5. Complete Implementations Complete
// Compliant: Complete implementation
async function authenticateUser(username, password) {
if (!username || !password) {
throw new Error('Username and password required');
}
try {
const response = await fetch('/api/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (!response.ok) {
throw new Error('Authentication failed');
}
const data = await response.json();
return data.token;
} catch (error) {
console.error('Auth error:', error);
throw error;
}
}
6. Simple and Clear Solutions Simple
// Compliant: Simple and clear
function getFirstItem(array) {
if (!array || array.length === 0) {
return undefined;
}
return array[0];
}
// Use simple object creation when appropriate
const config = {
apiUrl: process.env.API_URL,
timeout: 5000
};
7. Proper Validation and Assumptions Validation
// Compliant: Validate data structure
function getUserName(user) {
if (!user || !user.name) {
return 'Unknown User';
}
if (typeof user.name === 'string') {
return user.name;
}
if (user.name.first && user.name.last) {
return `${user.name.first} ${user.name.last}`;
}
return 'Unknown User';
}
8. Proper Imports and Dependencies Imports
// Compliant: Proper imports
import axios from 'axios';
import moment from 'moment';
import _ from 'lodash';
// Or use native alternatives
const response = await fetch('/api/data'); // Native fetch
const date = new Date().toISOString(); // Native Date
const mapped = array.map(fn); // Native array methods
9. Correct Variable Names and Logic Correct
// Compliant: Correct variable names
function getUser(id) {
const user = database.getUser(id);
if (!user) {
throw new Error('User not found');
}
return user.name;
}
function calculateTotal(items) {
let sum = 0;
for (let item of items) {
if (item && item.price) {
sum += item.price;
}
}
return sum;
}
// Compliant: Type checking
function addNumbers(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new TypeError('Both arguments must be numbers');
}
return a + b;
}
function processUser(user) {
if (!user || !user.name) {
throw new Error('Invalid user object');
}
return user.name.toUpperCase();
}
// TypeScript with proper types
function getData(id: number): Promise {
return database.get(id);
}
13. Configuration Management Config
// Compliant: Configuration
import config from './config';
function connectToDatabase() {
return new Database({
host: config.db.host,
port: config.db.port,
username: config.db.username,
password: config.db.password
});
}
function getApiUrl() {
return process.env.API_URL || config.apiUrl;
}
14. Proper Documentation Documented
/**
* Filters and processes an array of data items
* @param {Array} data - Array of data items to process
* @param {Object} options - Processing options
* @param {boolean} options.filter - If true, filters the data
* @returns {Array} Processed array of items
*/
function processData(data, options) {
if (!Array.isArray(data)) {
throw new TypeError('Data must be an array');
}
let result = data;
if (options && options.filter) {
result = data.filter(item => item !== null && item !== undefined);
}
return result;
}
Training developers on common AI-generated code issues
Understanding the importance of code review
Learning best practices for using AI coding assistants
Remember: Always review, test, and validate AI-generated code. Use AI as a starting point, not a final solution. Test thoroughly, check for security issues, and ensure code meets your project's standards.