Main Content
A better alternative to cutting and pasting code Archive - Originally posted on "The Horse's Mouth" - 2007-04-26 18:38:23 - Graham Ellis
If you're new to coding, you'll be so concerned to be writing code that works that you may not take a look at coding technique. Your nose will be so close to the grindstone as you work that you won't take the time to look and ask "Do I need to keep grinding anyway?"
If you find yourself writing a piece of code and thinking "surely someone has done this before", they probably have, and the code is probably available to you - either as a standard PHP function of in resource libraries such as the PEAR and PECL. ((See footnote for other languages))
If you find yourself cutting and pasting part of your code, then STOP! - you should be turning that code into a function ! "But I need to change a few things in the copy" I hear you saying. Maybe you do - and you have just identified those parts of the function code that will need to be passed in to it as parameters.
I wrote the text above in relation to PHP, but the same thing applies in almost every language.
In Perl, you write your shared code in a sub , and look on the CPAN resource library.
In Python, you write your shared code using a def , and look in the cheeseshop resource library.
In Java and C++ you write a method, in C a function , and in Tcl you write a proc . As I recall, in Fortran it's a subroutine or a function , and you may also come across words like macros and procedures ...
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) This article 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 Do not duplicate your code 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. This article Do not duplicate your code Functions and commands with dangerous names Call by name v call by value Passing arrays to procs in Tcl Variable Scope R104 - Control Structures Alternating valuses / flip-flop / toggle - example in Ruby Where does Ruby load modules from, and how to load from current directory Separating your code for easier testing, understanding and re-use; example in Ruby Finding sum, minimum, maximum and average in Python (and Ruby) Conditionals, loops and methods in Ruby - a primer with simple examples Learning to program - Loop statements such as while Learning to Program - the conditional statement (if) Muttable v immutable and implications - Ruby Finding the total, average, minimum and maximum in a program Ruby v Perl - a comparison example Assigning values to variables within other statements - Ruby Does a for loop evaluate its end condition once, or on every iteration? Multiple inputs, multiple out, ruby functions Is this number between? Does this list include? - Ruby How a for loop works Java, Perl and other languages Returning multiple values from a function call in various languages - a comparison Ruby training - some fresh examples for string handling applications Splitting data reading code from data processing code - Ruby Why do I need brackets in Ruby ... or Perl, Python, C or Java Alternative loops and conditionals in Ruby and Perl For loop - checked once, or evety time? Ruby v Perl comparison and contrast Passing code to procedures and yield in Ruby A short form of if ... then ... else Learning to program in Ruby - examples of the programming basics Ruby, Perl, Linux, MySQL - some training notes Ruby to access web services Ruby Programming Course - Saturday and Sunday What to do with a huge crop of apples Clean code, jump free (Example in Lua) Saying NOT in Perl, PHP, Python, Lua ... Some Ruby programming examples from our course Ruby, C, Java and more - getting out of loops for loop - how it works (Perl, PHP, Java, C, etc) This article Ruby's case - no break Equality in Ruby - == eql? and equal? Breaking a loop - Ruby and other languages 1st, 2nd, 3rd revisited in Ruby 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) This article Perl - $_ and @_ Do not duplicate your code 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 J706 - Objects and Classes Objects - from physical to virtual or abstract - Java Binomial Coefficient (Pascal Triangle) objects in Java Calculation within objects - early, last minute, or cached? Defining a static method - Java, Python and Ruby Looking inside Java classes - javap and javadoc When should I use OO techniques? Introduction to Object Oriented Programming Long, Longer, Longest in Java First Class Java. First step and moving forward. An example of Java Inheritance from scratch This article Class, static and unbound variables 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) This article PHP - static declaration Global, Superglobal, Session variables - scope and persistance in PHP A lazy programmer is a good programmer Do not duplicate your code 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 This article Do not duplicate your code