Writing Library Files
Problem
You notice that you’re writing similar code for common operations in several programs.
Solution
Put functions to perform those operations in a library file. Then you write the code only once.
Discussion
This section describes how to put code for common operations in
library files.
Encapsulation
(or
modularization)
isn’t really a
“recipe” so much as a programming
technique. Its principal benefit is that you don’t
have to repeat code in each program you write; instead, you just call
a function that’s in the library. For example, by
putting the code for connecting to the cookbook
database into a library function, you need not write out all the
parameters associated with making that connection. Simply invoke the
function from your program and you’re connected.
Connection establishment isn’t the only operation
you can encapsulate, of course. Later on in the book, other utility
functions are developed and placed in library files. All such files,
including those shown in this section, can be found under the
lib
directory of the recipes
distribution. As you write your own programs, you’ll
probably identify several operations that you perform often and that
are good candidates for inclusion in a library. The techniques
demonstrated in this section will help you write your own library
files.
Library files have other benefits besides making it easier to write programs. They can help portability. For example, if you write connection parameters into each program that ...
Get MySQL Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.