Sunday, January 11, 2009

Beware when Copy Pasting

Often times, a developer needs to copy code from one place and paste it at another place, followed by some minor modifications at the destination. Of course, copy pasting the same code at multiple places such that no modification would be needed isn’t a good practice and essentially, the developer must refactor and move the common code into a function and insert function calls at the appropriate places.

There are many scenarios where the former operation is required. Even though it is at times possible to move slightly variant code into a separate function and use parameters for the differing functionality, this might not always suffice for a multitude of reasons. The code might be getting used only in a couple of places for example. In such cases, the best way to reuse code is to copy paste. However, from my experience, most errors (often times so stupid that you won’t suspect them to be the cause of problems) occur when one forgets to make a particular change after pasting the code.

One major reason why one tends to miss one or two modifications is that a very minor/no change is needed when doing such reuse (of course, if major changes were needed then one should prefer rewriting code instead of reusing). So people just assume that no change is needed and leave the code as is. Some of the changes that are needed frequently include,

  1. Change of the value of a enum
  2. Change of index variable
  3. Changing the index value.
  4. Needing to declare a variable which was available for use in the copied code but not present at the place the code has been pasted.

Forget these kind of changes and you would spend another hour trying to find the issue and fixing it. Hence, be extra careful whenever copy-pasting code to be able to make the most of the time saving gained from not having to write the code again and in case some error crops up after you pasted code from somewhere, the first check you should make is whether the minor changes like the ones for variable names etc have been taken care of.

UPDATE : After discussions with Dinkar, one important point came up which was that such errors are more likely in Weakly typed languages for obvious reasons.

No comments:

Post a Comment