Refactor the code before you write it
Have you ever heard the saying “If you don’t know where to look, don’t look at all”? Think about this saying and coding. If a piece of code somewhere in the system is causing an error, don’t split the whole thing apart to find it. Know where to look for it before you cause even more damage.
The same principle can be applied to new features, functions or methods you want to create in your application. You know exactly how the feature has to work and you start coding. A lot of people start by writing proof-of-concept (POC) code first and then cleans it up and refactors it afterwards. Think of the saying and twist it a little, then it could sounds like this “If you don’t know how to write the code, don’t write it at all”.
That sounds a bit harsh, but in most cases it takes even longer to clean up the POC code and start refactoring than if you’ve already did it to begin with. Visualize how the code must be structured before you write everything in one very long method. It gives you that flexibility in the code you want when developing new things and the refactoring afterwards is kept to a minimum.
Another thing about POC code is, that in a busy day you might not get around to start cleaning your code right away and days, maybe weeks pass before you lay eyes on the code again. I’m not saying that POC code is a bad thing, but it does require a certain amount of discipline and time. If you visualize the code and refactor before you start writing, you’ll end up with a cleaner code in a shorter time.
My point has nothing to do with agile methods, TDD or any other methodologies for that matter. It has got to do with the preparation of the code you are gonna write before you write it. If you want to write a method called Publish() and you have an idea on how to do it, then I strongly believe that you have to visualize the method in your head before you start writing it. If you spend a minut just to think it through, you might just realize that you have to break the method up in smaller pieces. That eleminates the 100+ line methods and the cleaning and refactoring efforts afterwords are kept to a minimum.