Correggere i bug e migliorare il codice

Completato

Gli sviluppatori a volte possono scrivere codici che in linea di massima funzionano, ma che possono essere migliorati correggendo bug, sintassi, prestazioni o modularità. I modelli OpenAI di Azure consentono di identificare i modi per migliorare e fornire suggerimenti su come scrivere codici migliori.

Correggere i bug nel codice

I modelli OpenAI di Azure possono aiutare a risolvere i bug nel codice analizzando il codice e suggerendo modifiche che possono potenzialmente risolvere il problema. Ciò consente agli sviluppatori di identificare e risolvere i bug in modo più rapido e più efficiente.

Ad esempio, si supponga che la funzione seguente non funzioni per l'utente.

def calculate_average(numbers):  
    total = 0  
    for i in range(len(numbers)):  
        number = numbers[i]  
        total += number  
    average = total  
    rerun averave  
public double CalculateAverage(int[] numbers)
{
    int total = 0;
    for (int i = 0; i < numbers.Length; i++)
    {
        int number = numbers[i];
        total += number;
    }
    double average = (double)total;
    rerun averave;
}

Specificare tale funzione al modello, assieme al prompt Fix the bugs in this function: si otterrà una risposta con il codice fisso e una spiegazione di ciò che è stato risolto.

def calculate_average(numbers):  
    total = 0  
    for i in range(len(numbers)):  
        number = numbers[i]  
        total += number  
    average = total / len(numbers)  
    return average  
public double CalculateAverage(int[] numbers)
{
    int total = 0;
    for (int i = 0; i < numbers.Length; i++)
    {
        int number = numbers[i];
        total += number;
    }
    double average = (double)total / numbers.Length;
    return average;
}
There were a few issues with the original code:

1. The variable "average" was assigned the value of "total" instead of the actual average.
2. There was a typo in the last line - "rerun" should be "return".
3. The average was not actually calculated - the corrected code divides the total by the length of 
the "numbers" list to get the average.

Migliorare le prestazioni

Anche se il codice scritto dagli sviluppatori può funzionare, potrebbe esserci un modo più efficiente per eseguire l'attività. Ecco un esempio di una funzione che calcola la somma dei primi n interi positivi, presumibilmente in modo non efficiente:

def sum_of_n(n):
    result = 0
    for i in range(1, n+1):
        result += i
    return result
public int SumOfN(int n)  
{  
    int result = 0;  
    for (int i = 1; i <= n; i++)  
    {  
        result += i;  
    }  
    return result;  
}  

Questa versione funziona correttamente, ma la complessità del tempo è O(n). Quando viene fornita al modello, ecco la risposta:

We can improve this function it by using a mathematical formula instead.

Here's the more efficient version:
def sum_of_n(n):
    return n * (n + 1) // 2
public int SumOfN(int n)  
{  
    return n * (n + 1) / 2;  
}  

Questa versione restituisce comunque il risultato corretto, ma la complessità del tempo è ora O(1), che la rende molto più efficiente.

Refactoring codice inefficiente

Un codice migliore è meno soggetto a bug ed è più semplice da gestire; inoltre, i modelli OpenAI di Azure possono aiutare gli sviluppatori a eseguire il refactoring del codice.

Si consideri la funzione seguente.

def calculateTotalPrice(item, quantity):
    if item == 'apple':
        return quantity * 0.5
    elif item == 'banana':
        return quantity * 0.75
    elif item == 'orange':
        return quantity * 0.6
    else:
        return 0
public double CalculateTotalPrice(string item, int quantity)
{
    if (item == "apple")
    {
        return quantity * 0.5;
    }
    else if (item == "banana")
    {
        return quantity * 0.75;
    }
    else if (item == "orange")
    {
        return quantity * 0.6;
    }
    else
    {
        return 0;
    }
}

Questo codice calcola il prezzo totale di un particolare elemento in base al nome e alla quantità. Tuttavia, il codice non è modulare e può essere difficile da gestire. Quando viene fornito al modello con la richiesta di refactoring, ecco la risposta:

item_prices = {  
    'apple': 0.5,  
    'banana': 0.75,  
    'orange': 0.6  
}  

def calculate_total_price(item, quantity):  
    price = item_prices.get(item, 0)  
    return quantity * price  
static Dictionary<string, double> itemPrices = new Dictionary<string, double>()  
{  
    {"apple", 0.5},  
    {"banana", 0.75},  
    {"orange", 0.6}  
};  

static double CalculateTotalPrice(string item, int quantity)  
{  
    double price;  
    if (!itemPrices.TryGetValue(item, out price))  
    {  
        price = 0;  
    }  
    return quantity * price;  
}  

Assieme al codice, il modello fornisce una spiegazione del refactoring.

In this refactored code, we've created an object called itemPrices that maps item names to their 
prices. We've also simplified the calculateTotalPrice function by using the itemPrices object to look 
up the price of the item, rather than using a series of if/else statements. This makes the code more 
modular and easier to maintain, and also reduces the risk of introducing bugs in the future.