One, at the most!

Watching how somebody edited the code you wrote, can be an interesting exercise. I experienced difficult emotions on one such occasion, and amongst other things, there was bewilderment. Sometimes, I see unreasonable code and I'm perplexed whether I am missing some deeper meaning and purpose in those lines; if there's more than meets the eye!

Thanks to Github, I know who did it!

I had written some simple object initialisation code; a constructor, followed by some setters:

Contact c = new Contact();
c.Name = "Name";
c.Email = "Email";

There was a change in requirement. The object was given a new property, and conditionally, the property had to be set. The code was therefore modified to:

if (city == null) {
  Contact c = new Contact();
  c.Name = "Name";
  c.Email = "Email";
} else {
  Contact c = new Contact();
  c.Name = "Name";
  c.Email = "Email";
  c.City = "city";
}

The Virtue of Laziness

The first of the Three Virtues of a Programmer, Laziness, is not about taking shortcuts. It is about taking great effort today, in order to take much less effort tomorrow. If you are insightful about the code that you write, you will start perceiving potential 'problems' that a particular snippet of code can land you into. While it looks perfectly harmless, the above snippet lacks a basic code quality principle. If the initialisation of the object changes, or the default values assigned in this sample are modified, how many places will it impact the code? To which the ideal answer, in almost all circumstances, should be:

"One, at the most!".

And if you are looking for one more reason: it took effort to identify that other lines of code in both the blocks were exactly the same. And that is wasted time due to reduced readability in code.

Contact c = new Contact();
c.Name = "Name";
c.Email = "Email";
if (city != null) {
  c.City = "city";
}

The Passion for Quality

Of course, this is a very simplified example. But, one can see how the nasty "Copy-Paste" approach can lead to avoidable hurdles when you extrapolate this pattern to 'quick-fixes' done across the project. If you are passionate about code quality, it is not tools, but habits that will get you there. And here is a simple one to start with: When I have to change the code, will it be at just one location?