Refactoring: The Gilded Rose
It's time for another refactoring challenge. This time we will attempt a fun problem called The Gilded Rose Code Kata.
That original description of the problem was for C# developers and it didn't have things us Rubyists love, like tests. Luckily for us though, Jim Weirich ported the code to Ruby and added the tests as he did so. Let's use that version of the challenge.
As always, I recommend you try the refactoring before you read what I have to say about it. Being familiar with the problem will help you understand what we are dealing with below.
The first step in this problem is to get the code running locally. I started by pulling down Jim's code from GitHub:
$ git clone https://github.com/jimweirich/gilded_rose_kata.git Cloning into gilded_rose_kata... remote: Counting objects: 114, done. remote: Compressing objects: 100% (46/46), done. remote: Total 114 (delta 71), reused 109 (delta 66) Receiving objects: 100% (114/114), 15.38 KiB | 13 KiB/s, done. Resolving deltas: 100% (71/71), done. $ cd gilded_rose_kata
I use these Rubies in the Rough articles to teach how I think about code. Well, I have a scary admission to make: I didn't really understand refactoring until I was many years into being a programmer. Sure, I knew what it meant, but I just didn't get it. I hope to save you from the same mistake.
Refactoring is important. Very important. It may be one of the most important things we do as programmers. If I learned one thing from reading Smalltalk Best Practice Patterns, it's that code's primary purpose is to communicate with the reader. Let's face it though, when we are trying to get something working, it's often like stumbling around in the dark. We are running into all kinds of things, breaking stuff, and just trying to reach that "Holy cow it works!" moment. We're probably not thinking too long and hard about how well this mess we are making communicates and that's perfectly fine.
Refactoring is where you get to fix that. It's about taking working code and making it sexy. Note that I said it starts with working code. Until you have that, there's nothing worth communicating to a potential reader. Make it work, then make it sexy. (I believe that saying really involves speed, but that's a very different conversation we can have at a later date.)