Casi Studio: AI Anti-Patterns vs. Human Architect Fixes

🔬 Casi Studio: AI Anti-Patterns vs. Human Architect Fixes

Analisi Tecnica: Esempi reali di codice generato da LLM (vulnerabile o inefficiente) e la loro versione corretta dopo la Human Review.

::: info SCOPO DELLA PAGINA Questi esempi mostrano come l’applicazione della Checklist di Revisione trasformi un suggerimento probabilistico dell’IA in codice di grado industriale (Production-Ready). :::


🏗️ Caso 1: Gestione Memoria e RAII (C++)

❌ Proposta dell’IA (Stile Legacy/C-ish)

L’IA spesso genera codice che utilizza l’allocazione dinamica manuale, ignorando i principi del C++ moderno.

// AI Version: Rischi di Memory Leak se processData() lancia un'eccezione
void handleConnection(size_t bufferSize) {
    char* buffer = new char[bufferSize]; // Allocazione manuale
    
    if (!fillBuffer(buffer, bufferSize)) {
        delete[] buffer; // Necessità di cleanup manuale in ogni ramo
        return;
    }

    processData(buffer);
    
    delete[] buffer; // Facile da dimenticare
}

✅ Human Architect Fix (Modern C++ / RAII)

Applichiamo la regola: Mai usare new/delete espliciti. Usiamo lo stack o smart pointers.

/**
 * @brief Handles connection using RAII to ensure memory safety.
 * Fixed: Uses std::vector for automatic memory management.
 */
void handleConnection(size_t bufferSize) {
    // std::vector handles allocation/deallocation automatically (RAII)
    std::vector<char> buffer(bufferSize);

    if (fillBuffer(buffer.data(), buffer.size())) {
        processData(buffer.data());
    }
    // No manual delete needed: memory is freed even if an exception occurs
}

🛡️ Caso 2: Sicurezza ed Iniezione di Comandi (Python)

❌ Proposta dell’IA (Vulnerabile)

L’IA tende a usare stringhe f-string o concatenazioni per eseguire comandi di sistema, esponendo il sistema a Command Injection.

# AI Version: Se 'filename' contiene "; rm -rf /", il sistema viene distrutto
import os

def backup_file(filename: str):
    os.system(f"cp {filename} /backup/location/") # VULNERABILE

✅ Human Architect Fix (Sanitizzazione e Subprocess)

Applichiamo la regola: Separazione tra esecutore e argomenti.

import subprocess
import logging
from pathlib import Path

def backup_file(filename: str):
    """
    Fixed: Uses subprocess with argument list to prevent injection.
    Validates file existence using pathlib.
    """
    source_path = Path(filename)
    if not source_path.exists():
        logging.error(f"File {filename} not found.")
        return

    try:
        # Arguments are passed as a list, shell=False by default
        subprocess.run(["cp", str(source_path), "/backup/location/"], check=True)
    except subprocess.CalledProcessError as e:
        logging.error(f"Backup failed: {e}")

⚡ Caso 3: Efficienza Algoritmica e Prolissità (Python)

❌ Proposta dell’IA (Sub-ottimale e Prolissa)

L’IA spesso scrive loop estesi dove esistono funzioni built-in o idiomi più efficienti.

# AI Version: O(n) space and manual loop
def get_unique_elements(input_list):
    unique_list = []
    for item in input_list:
        if item not in unique_list: # O(n) lookup inside a loop = O(n^2)
            unique_list.append(item)
    return unique_list

✅ Human Architect Fix (Pythonic & Optimized)

Applichiamo la regola: KISS e complessità algoritmica.

from typing import List, Any

def get_unique_elements(input_list: List[Any]) -> List[Any]:
    """
    Fixed: Uses set for O(1) average lookup.
    Result: O(n) overall complexity instead of O(n^2).
    """
    # dict.fromkeys preserves order (Python 3.7+), set() would not.
    return list(dict.fromkeys(input_list))

📈 Tabella Comparativa delle Correzioni

CategoriaErrore Comune AISoluzione ArchitectVantaggio
C++ MemoryManual pointers (new)Smart Pointers / ContainersZero Memory Leaks
SecurityShell commands via stringssubprocess with list argsNo Command Injection
LogicMissing Edge CasesGuard Clauses / ValidationRobustezza estrema
DatabaseSQL string formattingPrepared Statements / ORMNo SQL Injection
PerformanceNested loops for lookupsHashing (Set/Dict)Scalabilità ($O(n)$)

💡 Lezione per il Wiki

::: warning CONCLUSIONE TECNICA L’IA genera codice basandosi sulla frequenza statistica, non sulla correttezza ingegneristica. Poiché il web è pieno di codice “vecchio” o di scarsa qualità, l’IA rifletterà quegli stessi difetti. La tua responsabilità è agire come un Senior Reviewer, applicando i moderni standard di sicurezza e performance che l’IA spesso ignora. :::


Tags: #CodeReview #SoftwareArchitecture #Security #Python #CPP #BestPractices*

Last updated on Tuesday, March 17, 2026
Built with Hugo
Theme Stack designed by Jimmy