AI vs Human - Kotlin Refactoring Showdown

Published: 10 January 2025
on channel: Pairing with Duncan
375
42

A key change that we can make to improve our code is to limit the scope of mutability - to program with calculations and values rather than actions. In contrast, the Kotlin code that the AI wrote for us to generate a Mermaid chart of test runtimes worked by recursively adding to a shared StringBuilder, making it hard to reason with and change.

Just for fun then, today we refactor the AI code to work with immutable lists, giving a simpler algorithm that I think better reflects the structure of the problem.

It was only having recorded this that I thought - I wonder if the AI could have fixed its own code? So I asked it, and it did.

I for one welcome our new AI overlords.

In this episode

00:00:45 Review the AI generated code
00:02:45 Convert to extension function
00:03:12 Extract a constant to the top level
00:04:16 Simplify output formatting
00:04:40 Un-nest the recursive function by passing it the state it mutates
00:07:49 Remove shared mutablity by giving functions their own mutable state
00:09:22 Now reduce mutablitity within the function
00:11:06 Revisit names when we change an action to a calculation
00:11:38 Indenting seems to be applied at the wrong level
00:12:30 Prefer List<String> to multi-line strings
00:15:12 Reduce the number of actions by calculating and batching
00:16:07 A change to the data model allows a better algorithm
00:17:24 Sealed interfaces make ad-hoc polymorphism work
00:18:08 How to handle optional things immutably
00:24:21 Now let the AI fix it's mess
00:29:04 Wrap up

There is a playlist of TDD Gilded Rose episodes -    • Test Driven Gilded Rose in Kotlin  
and one for testing    • Testing  

The codebase is available on GitHub https://github.com/dmcg/gilded-rose-tdd

If you are going to be at KotlinConf 2025, or even just in Copenhagen in May, then you should sign up for the workshop that Nat Pryce and I are running. It’s called Refactoring to Functional Kotlin, and will give you hands-on experience of taking legacy code and safely migrating it to a functional style. Places are limited, so buy now at https://kotlinconf.com/workhops

If you like this video, you’ll probably like my book Java to Kotlin, A Refactoring Guidebook (http://java-to-kotlin.dev). It's about far more than just the syntax differences between the languages - it shows how to upgrade your thinking to a more functional style.


Watch video AI vs Human - Kotlin Refactoring Showdown online without registration, duration hours minute second in high quality. This video was added by user Pairing with Duncan 10 January 2025, don't forget to share it with your friends and acquaintances, it has been viewed on our site 375 once and liked it 42 people.