Can ChatGPT refactor my bad code?

Francesco Mantovani
5 min readJan 30, 2023

Last week I went to ski.

While driving to the mountain the radio mentioned ChatGPT at least 3 times.

It’s evident that ChatGPT is eating the World.

So I asked to ChatGPT to refactor my

Bad code

The first impression is that you try to be polite and you treat the software like a human being.

I first asked if it was keen to refactor my code and the answer was a polite:

I’d be happy to help you with refactoring your script! However, without seeing the actual code and understanding the specific requirements and constraints of your use case, it will be difficult for me to provide specific suggestions for refactoring. If you could provide your script and more information about what you’re trying to accomplish, I can help guide you in refactoring the code to make it more efficient and readable.

Very good,

I copy/pasted my bad code: a script that iterate through all Azure SQL Database across all Azure Subscriptions and all Resource Groups:

#$ErrorActionPreference = ‘SilentlyContinue’

# Connect to Azure

$azureAccount = Connect-AzAccount

# Get Azure Access Token (we will use this to query the databasees)

#$azureToken = Get-AzAccessToken -ResourceUrl https://database.windows.net

$access_token = (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token

# Queries will be picked up from here

$folderPath = ‘.Queries’

# Choose how to format each date (“yyyy-MM-dd”) or (“yyyy-MM-dd HH:mm:ss”)

$DateTime = (Get-Date).ToString(“yyyy-MM-dd”)

# List Azure Sunscriptions

Get-Azsubscription | ForEach-Object -Begin { $a = 1 } -Process {“$a $($_.Name)”; $a++}

$SubscriptionChoice = Read-Host -Prompt “Copy/paste the name of the Subscription that you want to investigate. If more than one separate them by a coma, Type `”All`” if you want to target all of them”

# Iterate into subscriptoins and print names

foreach ($gs in $SubscriptionChoice) {

Select-Azsubscription -Subscription “$gs” | Out-Null

Write-Host “Let’s browse into Azure Sunscription: “ -NoNewline

Write-Host (Get-AzContext).Subscription.Name -ForegroundColor green

# Fins all Azure SQL Server

Get-AzSqlServer | ForEach-Object -Begin { $a = 1 } -Process {“$a $($_.ServerName)”; $a++}

$SqlServerChoice = Read-Host -Prompt “Copy/paste the name of the SQL Server that you want to investigate. If more than one separate them by a coma, Type `”All`” if you want to target all of them”

if ($SqlServerChoice = “All”){

$SqlServerChoice = Get-AzSqlServer

}

Foreach ($server in $SqlServerChoice){

$DatabaseChoice = Get-AzSqlDatabase -ServerName $server.ServerName -ResourceGroupName $server.ResourceGroupName | Where-Object DatabaseName -NE “master”

Foreach ($database in $DatabaseChoice){

(Get-ChildItem $folderPath | sort-object {if (($i = $_.BaseName -as )) {$i} else {$_}} ).Foreach{

Invoke-Sqlcmd -ServerInstance $server.FullyQualifiedDomainName -Database $database.DatabaseName -AccessToken $access_token -InputFile $psitem.FullName | Export-Csv -Path “.Results$psitem.csv” -Append -NoTypeInformation

write-host “Executing $psitem on $($database.DatabaseName)”

}

}

}

}

And the answer was:

Here are a few suggestions for refactoring your script:

Consider using the -ErrorAction parameter to handle errors instead of using $ErrorActionPreference. This allows you to handle errors on a case-by-case basis rather than globally.

Instead of using Out-Null after Select-Azsubscription, consider assigning the result of Select-Azsubscription to a variable, and then use that variable in the next operation. This can help make the code more readable and self-documenting.

Instead of using ForEach-Object to output the names of subscriptions and SQL servers and then reading the input from the user, consider using Out-GridView to display a GUI that allows the user to select one or more subscriptions or SQL servers.

Instead of using Where-Object to exclude the “master” database, consider using -ExcludeMasterDatabase parameter of the Get-AzSqlDatabase cmdlet.

You can use -AsJob parameter of the Invoke-Sqlcmd cmdlet to run the queries in parallel

Instead of using a foreach loop to iterate through the files in the folder, consider using Get-ChildItem and ForEach-Object to directly process the files.

Instead of using $psitem.FullName in the path of the export-csv cmdlet, you can use $_.FullName

Use -Confirm:$false on Remove-Item cmdlet if you are sure that you want to delete the files.

Use -WhatIf parameter on cmdlets to check what will happen if you execute the script.

Add comments to explain what the script is doing and why certain decisions were made.

Please note that these are just suggestions and you should test the script thoroughly after making any changes to ensure that it still functions as expected.

Fair enough.

All suggestions are correct.

But I was a bit upset as no new code was produced. I was expecting to be feed with a spoon…

And ChatGPT excused itself in the most polite way:

ChatGPT politeness

It cannot be over here.

I don’t want to work. I want you to work for me.

I want you to steal my job and I want me to be covered by the most Stalinian social welfare.

Go ahead ChatGPT, steal my job…

I go full Blade Runner mode. I now ask:

Can you create a PowerShell script that iterates through all Azure SQL Databases and Subscriptions and runs the query “SELECT @@VERSION” ? Thank you

(Note how polite I’m getting while talking with a chatbot.)

Sure, here’s a PowerShell script that iterates through all Azure SQL Databases and Subscriptions and runs the query “SELECT @@VERSION”:

# Connect to Azure

Connect-AzAccount

# Get Azure Access Token (we will use this to query the databases)

$access_token = (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token

# Iterate through all subscriptions

foreach ($subscription in (Get-AzSubscription)) {

Select-AzSubscription -SubscriptionId $subscription.Id

# Iterate through all SQL servers in the subscription

foreach ($server in (Get-AzSqlServer)) {

# Iterate through all databases on the server

foreach ($database in (Get-AzSqlDatabase -ServerName $server.ServerName -ResourceGroupName $server.ResourceGroupName)) {

# Run the query and output the results

Write-Host “Running query on $($database.DatabaseName) in $($server.ServerName)…”

Invoke-Sqlcmd -ServerInstance $server.FullyQualifiedDomainName -Database $database.DatabaseName -AccessToken $access_token -Query “SELECT @@VERSION”

}

}

}

Please note that you’ll need to have Azure PowerShell module installed and your machine should be authenticated to your azure tenant to run this script. Also, please test the script in a development environment first and make sure that it behaves as expected before running in a production environment.

I was amazed.

The code is reduced to the bone but you can indeed use it as a skeleton and adapt it to your goals.

I was speechless.

Conclusion

I read Sapiens, written by Yuval Noah Harari few years ago and I didn’t find it very interesting.

The chapter regarding the AI was too optimistic for me but I have to say that I was wrong. This ChatGPT looks very promising.

We all see how this is going to end, right? One day you’ll wake up and you have to choose between the blue pill and the red pill.

ChatGPT wife

--

--

Francesco Mantovani

Lorem Ipsum “Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit…” “There is no one who loves pain itself, who seeks