P M A J E W S K I

Please Wait For Loading

Chat GPT and refactor? - Software Developer's Tour

chatgpt_logo

Chat GPT and refactor?

In this post How to generate website using Chat GPT I checked how ChatGPT is doing with generating the layout.

Today, we will see how it copes with the refactoring.

Variables chain

var x = 5;
var a = x;
var b = a;
var c = b;
Console.WriteLine(c);
var d = c;
var e = d;
var f = e + 1;
var g = f;
var h = g;
Console.WriteLine(g);
chat gpt refactor

That’s not exactly what I meant.

Let’s try it differently.

chat gpt simplify

Much better.

Complicated LINQ

int[] numbers = { 1, 2, 3, 4, 5 };

var result = numbers
    .Where(n => n % 2 == 0)
    .Select(n => n * n)
    .OrderByDescending(n => n)
    .Skip(1)
    .TakeWhile((n, index) => index < 2 || n > 10)
    .Sum();

Console.WriteLine(result);

Okay, time to ask ChatGPT what can we do with this piece of code.

chat gpt attempt 4

I’m pasting here the code provided by ChatGPT, which allows you to verify that I’m not lying.

int[] numbers = { 1, 2, 3, 4, 5 };

var result = numbers
    .Where(n => n % 2 == 0)
    .Select(n => n * n)
    .OrderByDescending(n => n)
    .TakeWhile((n, index) => index < 2 || (index == 2 && n > 10))
    .Sum();

Console.WriteLine(result);

This code changes the result. The original code returned 4, but now it’s 20. Tell that to ChatGPT and watch how it will react.

chat gpt failure
int[] numbers = { 1, 2, 3, 4, 5 };

var result = numbers
    .Where(n => n % 2 == 0)
    .Select(n => n * n)
    .OrderByDescending(n => n)
    .TakeWhile((n, index) => index < 2 || (index == 2 && n > 10))
    .Sum();

Console.WriteLine(result);

Ok, let’s see.

Chat gpt wrong answer

ChatGPT said that this code would now return 4 as a result, but as you can see, it’s still 20.

My answer for this is

something went wrong
something went wrong

Yes, I know ChatGPT is capable of performing good refactoring, but we still need to double-check everything based on ChatGPT’s answer.

ChatGPT is wonderful tool, but again – it’s not medicine for every problem.

leave a comment