While working on a legacy application at work 2 days ago, I came across the following method that I wrote in 2011 and blogged about the problem I was trying to solve with it. Have a look at it and without reading the comment, see if you understand what the code does:
Right away, the method name screams at you, “I was stupidly conceived”. Obviously, AbraKaDabra is not the intent of the method and the method body doesn’t make it any easier for the reader to follow what the code is trying to do and why.
Now, look at the slightly refactored and cleaned up method and see if that is any clearer:
I am hoping you would see that the method name this time tells you its real intention, it tells you what its going to do and the method body smoothly takes you through the execution of that intent. I am sure there can be more improvements, but this version pretty much does the job. Although, this is a very simple example of clean code practices, but the principles apply just as well to more complex code and if the principles are followed rigorously then there won’t be any complex code.
Bottom line, you should revisit your old code whenever you can and make small improvements to it because what was cool back then may not be very maintainable now. In the words of Ward Cunnigham, “You know you are working on clean code when each routine you read turns out to be pretty much what you expected.”