DEV Community

loading...

Discussion on: Why Should You Refactor Your Code?

Collapse
kwstannard profile image
Kelly Stannard

I have a few real-world refactoring stories. The gist of each one take the following rough outline:

  • Realize doing something takes too long or is generating a lot of bugs.
  • Determine the source of the pain. This is usually an anti-pattern or just bad practice.
  • Remember the correct way to fix the pain.
  • Rewrite the part causing the pain with the correct fix.

For a real world example, I had been using the ClassyHash gem fairly extensively as part of a project. I needed to start extending it for more specific test cases than were possible by default with classy hash. I tried for a day to make my own extension and it was like pulling teeth. Realizing I was pulling teeth was step one.

Next I had seen that there was a giant conditional statement at the heart of ClassyHash. I know big conditionals are bad practice. I had found the source of the pain.

Third, I know that polymorphism is the fix for conditionals.

Finally, I rewrote the whole gem in the course of 4 hours including tests.

So, what did this gain me? After the re-write I could write an extension with tests in 10-20 minutes, an order of magnitude development speed increase.

Collapse
jamesmh profile image
James Hickey Author

Nice! It's an awesome feeling when you come back to that task you were trying so hard to pull-off, and it takes a fraction of the time to do and is just really simple and straightforward now. 🥳