Chapter 5 Reusing Code and Writing Functions
Over the useful life of a piece of software,significantly more time will be spent main-
taining,modifying,testing, and documenting it than was originally spent writing it.If
you are writing commercial code,you should attempt to limit the number of lines in use
within the organization.One of the most practical ways to achieve this goal is to reuse
code already in use instead of writing a slightly different version of the same code for a
new task.Less code means lower costs.If existing software meets the requirements of the
new project,acquire it.The cost of buying existing software is almost always less than the
cost of developing an equivalent product.Tread carefully,though,if existing software
almost meets your requirements. Modifying existing code can be more difficult than
writing new code.
If a module of code is in use somewhere in your organization,it has presumably already
been thoroughly tested. Even if this module contains only a few lines,there is a possibili-
ty that,if you rewrite it,you will either overlook something that the original author
incorporated or something that was added to the original code after a defect was found
during testing.Existing,mature code is usually more reliable than fresh,“green”code.
The external interfaces to your system,including both user interfaces and interfaces to
outside systems,should be consistent.Writing new code consistent with the way other
parts of the system function takes a will and a deliberate effort. If you are reusing code
that runs another part of the system,your functionality should automatically be
On top of these advantages,reusing code is less work for you,as long as the original
code was modular and well written.While you work,try to recognize sections of your
code that you might be able to call on again in the future.
PHP provides two very simple,yet very useful,statements to allow you to reuse any type
of code.Using a
statement,you can load a file into your PHP
script.The file can contain anything you would normally type in a script including PHP
statements,text,HTML tags,PHP functions,or PHP classes.
These statements work similarly to the server-side includes offered by many web
statements in C or C++.