Main Content

Do not duplicate your code

Archive - Originally posted on "The Horse's Mouth" - 2006-06-23 07:13:33 - Graham Ellis

If you've writing or maintaining a program and you find yourself cutting and pasting a chunk of code, STOP and think again.

By duplicating a block of code, you're duplicating your maintainance task from that point onwards - any fixes applied to the original much be applied to the copy too. And that's going to be very inefficient in time as you duplicate the duplicate and end up with a whole shed load of copies. There IS a better way!

Take the code that you would be duplicating, and put it somewhere separate. Give it a name (i.e. make it a named block of code) and call it up by name from both its original location, and from the location that you would have put the copy into. All modern languages support named blocks of code in this way:
• In Perl, they're known as subs which is short for subroutines
• In many other languages, they're known as functions or methods or macros
• In Tcl, they're known as procs which is short for procedures

"But I want to make a couple of changes to the block of code that I was going to duplicate" you might say. That's NOT a problem. The bits that you would change in the duplicated code are the bits that you'll pass in to your sub / function / method / procedure as parameters, and if you also change the variable that the result is going to be put into, that's the immediate clue as to what you'll be returning.

Where you want to share a named block of code between several programs, you can do so too. That's done through commands / calls such as import (Python, Java), source (Tcl), require (Perl, PHP), use (Perl), from (Python) and include (PHP). In C and C++, functions work across programs in a slightly different way - rather than including the reference in the source, you'll bring in prototypes in the source and then the full code in your link loader. But that's a story for another day ...