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 ...