When working with a code base I often get into the situation where I find a piece of code that I do not understand the purpose of. I might see that it actually do something because it is called from other parts of the system, but I cannot see why, what purpose it does fill. Such a piece of code runs a lot of risk to fall under the axe, be thrown away, and replaced.
Is that not unfair? How do I dare just to discard someone else piece of work and replace it with my own? How would I react if someone else did that to my carefully crafted solutions?
Every time a programmer is about to modify or extend a piece of code, then that code stand in front of a higher court and have to justify its existence. If the code cannot convincingly plead its case, it will probably go into the land of beyond, i e into the version control attic. And in that trial, being some long windily method with non-descriptive name and having neither javadoc, nor unit tests will be equal to saying nothing to your defence.
But still, is that not unfair? Well, that might seems so, but obviously the original programmer has not thought it worthwhile to spend one minute to motivate its design. And in that case, what motivates that I spend ten minutes on trying to reconstruct the motivations? Is my time worth just a tenth of the other programmer's? To me this is much about courtesy from one programmer to another - paying respect to each others time.
To return to the code on trial; how do I try to save my code in future trials, when I might not be present in person? I try to equip them with a possibility to plead their case for themselves. I give each public method at least one single sentence of javadoc that in plain language explains, or at least indicates, the purpose it fulfil. And by just that I drastically increase the chances that the method will be understood and left to live.
Whenever possible, and that is not always the case working deep inside already existing code, I try to strengthen the case by adding objective proofs of the code's fitness, in the form of executable tests. Here the purpose of each test is to prove some aspect of the code, e g that in a set the removal of an element is independent of how many times it is added. Here again, the names of the test methods should indicate the purpose of the test, e g testShouldDeleteElementFromSetOnRemoveEvenAfterMultipleAdds. Please check out some of Dan North's writing on behaviour driven development to get some more ideas. But again, the test will help to plead the code's case and make it stay alive for yet some time.
So to radically increase your code's probability of survival, ensure on your next commit that every public class, method, or field is equipped with a proper plead of self defence in the form of at least one single sentence that explains its purpose. It is the least you can do for your creation.
Yours
Dan