I’m not talking about code that was written by someone else or was written years ago and is no longer used. I’m talking about code that you wrote 5 minutes ago. But why delete code you wrote 5 minutes ago?

A lot of software developers are afraid to write code that they may not need later. And they’re terrified to write code they know they won’t need later. We’ll discuss the problem endlessly before we even try one of the solutions. I was definitely there not too long ago and I still struggle with it.

It seems we set off to write a use case with a general idea of what we want. Class names, method signatures, dependencies, we’ve got it nailed down. But then, suddenly, a change comes in we weren’t expecting. That class is now not working out so well. But we can’t just get rid of it! We put so much work into it!

Learning to delete code was one of the biggest obstacles I faced to learning TDD. I couldn’t believe that even though I knew (or thought I knew) where I wanted to go I would take these small steps to get there that would most likely end up going away in a little while. Why would you do that?!

I had an “a-ha” moment at a group pairing event lead by @dwhelan. As we got started I said something like, “I don’t understand, how do I take the first step wen I don’t even have a class or a method to do anything? Would I write something dumb like verify_class_exists()?” To which he replied, “Sure, why not?” Begrudgingly, I wrote that test. But after a couple more tests, that one seemed superfluous. Thinking I had gotten one over on Declan, “But now that first test that checks for the class existing is useless! These other tests incidentally verify that the class exists and, besides, the compiler always assured us that the class existed!” “If you don’t need it anymore, why not delete it?” It was that moment where the tide turned from TDD being a theoretical thing that seemed powerful into a tangible practice that I knew how to do. It wasn’t easy but at least I knew how to take the first steps.

Give it a shot sometime. If you don’t know how to write that next test, write something stupid like “such_and_such_method_should_exist” or “this_function_will_take_3_arguments”. It does wonders for getting you unstuck and really gets the creative juices flowing. Then delete it when it becomes redundant; a small price to pay for getting unstuck. The next time you want to drastically change a method signature, instead of changing it and then finding all the callers over the next few days/weeks, create a new method, delegate the old method to it, go around and update the callers, then delete the old method. Having the code compile and run the whole time is a great feeling. Yes, you’ll be doing some extra steps that you know you will delete in 5 minutes but the journey is very satisfying. Plus you end up getting there quicker and without any surprises when the code goes into production. It may be overkill sometimes but I find it’s a good tool to have around.