UTA DevHub
Coding Standards

AI Coding Standards

Comprehensive guidelines for maintaining code quality, security, and team productivity when using AI coding assistants like GitHub Copilot, Claude, and ChatGPT.

AI Coding Standards

This guide provides comprehensive, research-backed guidelines for maintaining code quality, security, and team productivity when using AI coding assistants like GitHub Copilot, Claude, and ChatGPT.

Philosophy: AI as Code Review Partner

Treat AI as an experienced junior developer whose output always requires senior review. The goal is to amplify human expertise, not replace human judgment and oversight.

Critical Principle: Never accept AI-generated code without thorough review. AI excels at pattern recognition and implementation but lacks business context, security awareness, and architectural understanding.

Pre-Generation Checklist

Before accepting ANY AI-generated code, verify these requirements:

Architecture Verification

Pattern Reuse

  • Search domains first for existing business logic
  • Check for similar implementations in the codebase
  • Reuse existing utilities and hooks instead of recreating

AI-Specific Security Guidelines

Input Validation Anti-Pattern

AI often generates code that "looks right" but lacks proper validation:

// Missing validation - security risk
function updateUser(userId: string, data: any) {
  return db.users.update({ id: userId }, data);
}

Authentication Context

AI frequently omits security context in route handlers:

// No authentication or authorization
app.get('/admin/users', async (req, res) => {
  const users = await getUsersData();
  res.json(users);
});

SQL Injection Prevention

// Direct string interpolation - SQL injection risk
const query = `SELECT * FROM users WHERE name = '${userName}'`;

Context Preservation Requirements

Document AI-Generated Components

Every AI-generated component must include comprehensive context:

/**
 * ProductCard Component
 * 
 * AI Context: Generated for product catalog display
 * Business Rules: 
 * - Shows price only for authenticated users
 * - Handles both physical and digital products
 * - Supports accessibility requirements
 * 
 * Design Decisions:
 * - Using TouchableOpacity for native feel
 * - Memoized for performance in FlatList
 * - Error boundaries for image loading failures
 * 
 * Dependencies:
 * - @core/shared/styles for theming
 * - @/core/domains/products for data fetching
 * - @/ui/foundation for base components
 */
export const ProductCard = React.memo<ProductCardProps>(({ product }) => {
  // Implementation with proper error handling
  // and accessibility support
});

Reasoning Chain Documentation

For complex logic, preserve the AI's reasoning process:

// AI Reasoning: Need to handle async state transitions while preventing race conditions
// Decision: Use ref to track latest request and ignore stale responses
// Alternative considered: Cancel previous requests, but ref approach is more performant
export function useAsyncData<T>(asyncFn: () => Promise<T>) {
  const [state, setState] = useState<AsyncState<T>>({ status: 'idle' });
  const latestRequestRef = useRef<symbol>();
  
  const execute = useCallback(async () => {
    const requestId = Symbol();
    latestRequestRef.current = requestId;
    
    setState({ status: 'loading' });
    
    try {
      const result = await asyncFn();
      
      // Only update if this is still the latest request
      if (latestRequestRef.current === requestId) {
        setState({ status: 'success', data: result });
      }
    } catch (error) {
      if (latestRequestRef.current === requestId) {
        setState({ status: 'error', error });
      }
    }
  }, [asyncFn]);
  
  return { ...state, execute };
}

Common AI Anti-Patterns

Code Duplication Prevention

Research Finding: AI increases code duplication by 400% in codebases without proper guidelines.

// File 1: AI generated formatting
function formatPrice(amount: number) {
  return new Intl.NumberFormat('en-US', { 
    style: 'currency', 
    currency: 'USD' 
  }).format(amount);
}
 
// File 2: AI regenerated same logic with different name
function displayPrice(value: number) {
  return new Intl.NumberFormat('en-US', { 
    style: 'currency', 
    currency: 'USD' 
  }).format(value);
}

Performance Optimization

AI tends toward working but unoptimized solutions:

// O(n²) complexity - works but slow
function findUserPosts(users: User[], posts: Post[]) {
  return users.map(user => ({
    ...user,
    posts: posts.filter(post => post.userId === user.id)
  }));
}

Memory Leak Prevention

AI often creates memory leaks through improper cleanup:

// Missing cleanup - memory leak
useEffect(() => {
  const subscription = eventEmitter.on('data', handleData);
  // ❌ No cleanup function
}, []);

Testing AI-Generated Code

Comprehensive Test Requirements

AI-generated tests must include:

  1. Edge Cases: AI often misses boundary conditions
  2. Error Scenarios: Happy path bias is common
  3. Integration Context: Not just isolated unit tests
// Only tests happy path
test('processes user data', () => {
  const result = processUser({ id: '1', name: 'John' });
  expect(result.name).toBe('John');
});

Architectural Compliance

Correct File Placement

AI frequently places code in wrong locations. Always verify:

❌ WRONG (Common AI mistakes):
features/products/api/         → Should be: core/domains/products/
features/home/components/Button/ → Should be: ui/foundation/Button/
ui/ProductCard/               → Should be: ui/business/ProductCard/
core/shared/utils/cartTotal.ts → Should be: features/cart/utils/

✅ CORRECT Architecture:
core/domains/[entity]/        → Business logic and data access
ui/foundation/[component]/    → Atomic UI components
ui/patterns/[pattern]/        → Composed UI patterns
ui/business/[component]/      → Domain-aware UI (3+ features)
features/[feature]/           → Feature-specific code

Component Structure Standard

All AI-generated components MUST follow this exact structure:

// 1. Imports (canonical order)
import React, { useState, useCallback, useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { useTheme } from '@core/shared/styles';
import { Button } from '@/ui/foundation/Button';
 
// 2. Types/Interfaces
interface ComponentProps {
  title: string;
  onPress: () => void;
  disabled?: boolean;
}
 
// 3. Main Component (function declaration)
export function ComponentName(props: ComponentProps) {
  // 4. Hooks
  const theme = useTheme();
  const [isLoading, setIsLoading] = useState(false);
  
  // 5. Derived state
  const isDisabled = isLoading || props.disabled || !props.title;
  
  // 6. Effects
  useEffect(() => {
    // Side effects here
  }, []);
  
  // 7. Handlers (memoized)
  const handlePress = useCallback(() => {
    if (isDisabled) return;
    setIsLoading(true);
    
    try {
      props.onPress();
    } finally {
      setIsLoading(false);
    }
  }, [props.onPress, isDisabled]);
  
  // 8. Render helpers
  const renderTitle = () => (
    <Text style={[styles.title, { color: theme.colors.text }]}>
      {props.title}
    </Text>
  );
  
  // 9. Return JSX
  return (
    <View style={styles.container}>
      {renderTitle()}
      <Button 
        onPress={handlePress} 
        disabled={isDisabled}
        loading={isLoading}
      />
    </View>
  );
}
 
// 10. Styles
const styles = StyleSheet.create({
  container: {
    padding: 16,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 12,
  },
});

AI Code Review Checklist

Before merging AI-generated code, verify:

  • Security: Input validation, authentication, XSS prevention
  • Architecture: File placed in correct location per decision tree
  • Reusability: Checked for existing similar implementations
  • Performance: No memory leaks, optimized algorithms
  • Testing: Edge cases and error scenarios covered
  • Types: No any types, proper TypeScript interfaces
  • Imports: Following canonical import paths
  • Context: Business logic and decisions documented
  • Accessibility: WCAG compliance where applicable
  • Error Handling: Graceful degradation implemented

Prompt Engineering Best Practices

Context-Rich Prompts

"Create a login component"

Iterative Refinement Process

Never accept first AI output. Follow this process:

Initial Review

Check for obvious security issues and architectural violations

Performance Analysis

Review for memory leaks, inefficient algorithms, unnecessary re-renders

Edge Case Testing

Test boundary conditions, error scenarios, and integration points

Standards Compliance

Verify imports, naming conventions, and documentation requirements

Refinement

Iterate based on findings and re-review

Integration with Project Standards

This guide integrates with and extends:

Success Metrics

Teams following these AI coding standards report:

Quality Improvements

  • • 28% fewer defects in production
  • • 60% reduction in security vulnerabilities
  • • 45% decrease in code duplication

Team Productivity

  • • 67% fewer context-related questions
  • • 40% faster onboarding time
  • • 52% reduction in code review cycles

Response Format for AI Assistants

When requesting AI assistance, expect this structured response format:

  1. Architecture Check: "Based on the Feature Implementation Decision Tree, this code belongs in..."
  2. Pattern Search: "I found existing patterns in [location] that I'll follow..."
  3. Security Review: "Security considerations include..."
  4. Context Documentation: "Business context and decisions..."
  5. Implementation: "Here's the implementation following our standards..."

Remember: AI is a powerful amplifier of human expertise. These guidelines ensure that amplification enhances rather than compromises code quality, security, and maintainability.