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 sub s which is short for subroutines
• In many other languages, they're known as functions or methods or macros
• In Tcl, they're known as proc s 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 ...
Some other articles
Y105 - Functions, Modules and Packages From and Import in Python - where is the module loaded from? Embedding more complex code into a named block Nesting decorators Recursion in Python - the classic example What are callbacks? Why use them? An example in Python What is the difference between a function and a method? Reading command line parameters in Python A good example of recursion - a real use in Python Python - even named code blocks are objects Multiple yields and no loops in a Python generator? Python functions - an introduction to how they work Python varables - checking existance, and call by name or by value? Exception, Lambda, Generator, Slice, Dict - examples in one Python program vargs in Python - how to call a method with unknown number of parameters Optional positional and named parameters in Python Default local - a good choice by the author of Python Static variables in Python? Python timing - when to use a list, and when to use a generator Functions are first class variables in Lua and Python Finding all the unique lines in a file, using Python or Perl Python Packages - groupings of modules. An introduction Static variables in functions - and better ways using objects Passing optional and named parameters to python methods Catching the fishes first? Passing parameters to Python functions - the options you have Returning multiple values from a function call in various languages - a comparison Using an exception to initialise a static variable in a Python function / method Python - some common questions answered in code examples Passing a variable number of parameters in to a function / method Program for reliability and efficiency - do not duplicate, but rather share and re-use Optional and named parameters to Python functions/methods Python - access to variables in the outer scope Global and Enable - two misused words! Good example of recursion in Python - analyse an RSS feed Sample code with errors in it on our web site Optional parameters to Python functions Multiple returns from a function in Python Conversion of OSI grid references to Eastings and Northings Dynamic code - Python Optional and named parameters in Python What to do with a huge crop of apples Anonymous functions (lambdas) and map in Python Sharing variables with functions, but keeping them local too - Python Global - Tcl, PHP, Python Python Script - easy examples of lots of basics Returning multiple values from a function (Perl, PHP, Python) A better alternative to cutting and pasting code Function / method parameters with * and ** in Python It's the 1st, not the 1nd 1rd or 1th. Sludge off the mountain, and Python and PHP Python - A list of methods Recursion in Python Python - function v method Dynamic functions and names - Python This article Cottage industry or production line data handling methods Python modules. The distribution, The Cheese Shop and the Vaults of Parnassus. Python - block insets help with documentation Python's Generator functions Difference between import and from in Python What is a callback? Code and code maintainance efficiency Call by name v call by value Lambdas in Python Python generator functions, lambdas, and iterators Distance Learning Variable Scope T207 - Procedures and Variable Scope Accessing variables across subroutine boundaries - Perl, Python, Java and Tcl Sharing lots of values in Tcl without having lots of global declarations Passing back multiple results in Tcl - upvar and uplevel Tcl - Some example of HOW TO in handling data files and formats Passing a variable number of parameters in to a function / method Global and Enable - two misused words! Tcl - uplevel to run code at calling level Tcl - passing arrays and strings in and back out of procs Calling procs in Tcl and how it compares to Perl Tcl - global, upvar and uplevel. A better alternative to cutting and pasting code This article Functions and commands with dangerous names Call by name v call by value Passing arrays to procs in Tcl Variable Scope P209 - Subroutines in Perl Learning to use existing classes in Perl Perl functions such as chop change their input parameters Separating groups of variables into namespaces Passing a variable number of parameters in to a function / method Fresh Perl Teaching Examples - part 2 of 3 Do not copy and paste code - there are much better ways Efficient calls to subs in Perl - avoid duplication, gain speed Romeo and Julie Seven new intermediate Perl examples Daisy the Cow and a Pint of Ginger Beer Perl - Subs, Chop v Chomp, => v , Global - Tcl, PHP, Python Calling procs in Tcl and how it compares to Perl Returning multiple values from a function (Perl, PHP, Python) A better alternative to cutting and pasting code Perl - $_ and @_ This article Changing @INC - where Perl loads its modules Packages in packages in Perl Where do Perl modules load from Call by name v call by value Variable Scope H105 - Functions Coding efficiency - do not repeat yourself! Passing a variable number of parameters in to a function / method Improving your function calls (APIs) - General and PHP Adding extensions to PHP Open Source applications - callbacks Static variables and ampersands in PHP A variable number of arguments in a PHP function Global - Tcl, PHP, Python Static variables in PHP Clean my plate, but keep my wine bottle. (PHP; Static) is there a lookup function in php? Returning multiple values from a function (Perl, PHP, Python) A better alternative to cutting and pasting code PHP - static declaration Global, Superglobal, Session variables - scope and persistance in PHP A lazy programmer is a good programmer This article Don't repeat code - use loops or functions Functions and commands with dangerous names Code and code maintainance efficiency Passing information into and out of PHP functions Call by name v call by value There is a function in PHP to do that Variable Scope C204 - Functions, Macros and programs in multiple files Function prototype - what they are and why you should use them - C and C++ Preprocessor directives in C and C++ - what they mean Passing information into functions in C - by name, by value Passing arrays into functions in C Naming blocks of code, structures and Object Orientation - efficient coding in manageable chunks Returning extra results from a function in C Using functions to keep look and feel apart from calculations - simple C example C Course exercise and sample answer - source in 2 files Sharing variables between files of code in C - extern Function Prototypes in C Some new C programming examples - files, structs, unions etc A better alternative to cutting and pasting code This article