paint-brush
Here's What Your AI-Generated Code Is Not Telling Youby@tirtha
781 reads
781 reads

Here's What Your AI-Generated Code Is Not Telling You

by Tirtha SarkerMarch 26th, 2025
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

AI-powered IDEs are changing how we code. But there’s a technical reality we need to address: AI doesn’t just accelerate coding— it also accelerates bugs.

Company Mentioned

Mention Thumbnail
featured image - Here's What Your AI-Generated Code Is Not Telling You
Tirtha Sarker HackerNoon profile picture
0-item


AI-powered IDEs are changing how we code — faster development, fewer boilerplate headaches, and instant suggestions. But there’s a technical reality we need to address:


AI doesn’t just accelerate coding — it also accelerates bugs. 💥


After working with Cursor, Copilot and Windsurf in different environments, I’ve noticed AI doesn’t typically produce “wrong” code. Instead, it generates technically correct solutions that miss crucial business context and domain knowledge.

Here’s what AI coding assistants typically get wrong:

1. AI Introduces Subtle, Hard-to-Spot Performance Issues

❌ AI Suggestion: Looks efficient but has a subtle N+1 query problem


const getUsersWithOrders = async (): Promise<UserWithOrders[]> => {
  // Fetch all users - seems reasonable
  const users = await prisma.user.findMany({
    where: { status: 'ACTIVE' }
  });
  
  // For each user, get their orders - the subtle N+1 query issue
  const usersWithOrders = await Promise.all(
    users.map(async (user) => {
      const orders = await prisma.order.findMany({
        where: { userId: user.id },
        orderBy: { createdAt: 'desc' },
        take: 5 // Just get recent orders
      });
      return { ...user, orders };
    })
  );
  
  return usersWithOrders;
};

✅ Better Solution: Single efficient query with proper relations

const getUsersWithOrders = async (): Promise<UserWithOrders[]> => {
  // One efficient query with proper inclusion of related data
  const users = await prisma.user.findMany({
    where: { status: 'ACTIVE' },
    include: {
      orders: {
        orderBy: { createdAt: 'desc' },
        take: 5,
      }
    }
  });
  
  // Server-side data transformation if needed
  return users.map(user => ({
    ...user,
    orders: user.orders,
    // Transform any data if required
    totalSpent: user.orders.reduce((sum, order) => sum + order.total, 0)
  }));
};

2. AI Misses Contextual Constraints When Integrating With Existing Codebases

interface User {
  id: string;
  name: string;
  email: string;
}

const getUserDetails = async (userId: string): Promise<User> => {
  const response = await fetch(`/api/users/${userId}`);
  if (!response.ok) throw new Error('Failed to fetch user');
  return await response.json();
};

✅ Better Solution: Following established application patterns

import { ApiService } from '@/services/api';
import { User } from '@/types/user';
import { handleApiError } from '@/utils/error-handling';

export const getUserDetails = async (userId: string): Promise<User> => {
  try {
    return await ApiService.get<User>(`users/${userId}`);
  } catch (error) {
    return handleApiError(error, 'Failed to fetch user details');
  }
};

3. AI Makes Reasonable Assumptions But Misses Domain-Specific Requirements

❌ AI Suggestion: Technically correct discount calculation

const calculateDiscount = (price: number, discountPercent: number): number => {
  const discountAmount = price * (discountPercent / 100);
  return price - discountAmount;
};

✅ Better Solution: Incorporates business rules and formatting

const calculateDiscount = (price: number, discountPercent: number): number => {
  // Company policy: Maximum discount is 40% unless approved
  const effectiveDiscount = Math.min(discountPercent, 40);
  
  // Business rule: Discounts are calculated after tax in our system
  const priceWithTax = addTax(price);
  
  const discountAmount = priceWithTax * (effectiveDiscount / 100);
  
  // Format to company standard: always round to nearest cent
  return Number((priceWithTax - discountAmount).toFixed(2));
};

🚀 The Truth? AI Doesn’t Write Bad Code — It Just Can’t Read Your Mind

The pattern is clear: AI excels at generating syntactically correct, algorithmically sound code. What it consistently misses are:

  1. Business context and domain rules — it can’t know your specific company policies
  2. Project-specific conventions — it has limited understanding of your codebase’s patterns
  3. Architectural implications — it focuses on the function at hand, not the system as a whole
  4. Performance at scale — optimizations that matter in production environments

✅ How to Use AI Tools Effectively

1. Reserve AI for boilerplate, but review integration points carefully — AI excels at generating repetitive patterns but often misses how components connect in larger systems.

2. Craft precise prompts with context –

  • 🚫 “Generate a TypeScript React hook for data fetching”
  • ✅ “Generate a TypeScript React hook for data fetching that follows our existing error handling pattern, includes cleanup on unmount, and handles stale requests”

3. Verify edge cases AI might miss.


describe('calculateDiscount', () => {
  it('correctly calculates a 20% discount on $100', () => {
    expect(calculateDiscount(100, 20)).toBe(80);
  });
  it('handles zero price', () => {
    expect(calculateDiscount(0, 15)).toBe(0);
  });
  it('handles zero discount', () => {
    expect(calculateDiscount(50, 0)).toBe(50);
  });
  it('handles decimal precision correctly', () => {
    expect(calculateDiscount(9.99, 10)).toBe(8.99);
  });
  it('rejects negative prices', () => {
    expect(() => calculateDiscount(-10, 20)).toThrow();
  });
  it('rejects invalid discount percentages', () => {
    expect(() => calculateDiscount(100, 101)).toThrow();
    expect(() => calculateDiscount(100, -5)).toThrow();
  });
});


These aren’t “bugs” in the traditional sense, but rather a fundamental limitation: AI can’t understand your business domain, company standards, or the full context of your application architecture the way a seasoned team member can.


🚀 Bottom Line? AI is a powerful tool, but it’s not your CTO. Think critically. Review aggressively. Code smart.


📢 “The Engineer’s Log” is where we decode the world of AI, Web3, and software engineering — without the BS. Subscribe for deep dives, best coding practices, and real-world debugging stories.

🛠 Join the newsletter → The Engineer’s Log