OReilly.Oracle.PLSQL Best Practices

Term Fly Presents


Oracle PL/SQL Best Practices
By St even Feuerst ein

: O'Reilly

Pub Dat e

: April 2001


: 0- 596-00121-5


: 202

Or a cle PL/ SQL Be st Pr a ct ice s is a con cise , e a sy- t o- u se su m m a r y of be st
pr a ct ice s in t h e pr ogr a m de ve lopm e n t pr oce ss. I t cov e r s codin g st yle ,
w r it in g SQL in PL/ SQL, da t a st r u ct u r e s, con t r ol st r u ct u r e s, e x ce pt ion
h a n dlin g, pr ogr a m a n d pa ck a ge con st r u ct ion , a n d bu ilt - in pa ck a ge s.
Com ple m e n t a r y code e x a m ple s a r e a va ila ble on t h e O'Re illy w e b sit e .
I n clu de s a pu ll- ou t qu ick - r e fe r e n ce ca r d.

Pr e fa ce
When I first st art ed w rit ing about t he Oracle PL/ SQL language back in 1994, t he only
sources of inform at ion were t he product docum ent at ion ( such as it was) and t he
occasional paper and present at ion at Oracle User Group ev ent s. Today, t here are at
least a dozen books t hat focus exclusively on PL/ SQL, num erous product s t hat help
you w rit e PL/ SQL code ( int egrat ed dev elopm ent environm ent s, knowledge bases,
et c.) , t raining classes, and web sit es. And t he com m unit y of PL/ SQL developers
cont inues t o grow in size and m at urit y, even wit h t he advent of Java.
Access t o inform at ion about PL/ SQL is no longer t he challenge. I t can, on t he ot her
hand, be difficult t o m ake sense of all t he new feat ures, t he num erous resources, t he
choices for t ools, and so on. When it com es t o w rit ing a program or an ent ire
applicat ion, developers have, ov er and over again, expressed t he desire for advice.
They ask:

How should I form at m y code?
What nam ing convent ions, if any, should I use?
How can I writ e m y packages so t hat t hey can be m ore easily m aint ained?
What is t he best way t o query inform at ion from t he dat abase?
How can I get all t he developers on m y t eam t o handle errors t he sam e way?

So m any quest ions, so m uch burning desire t o writ e code w ell, and so few resources
available t o help us do t hat .
So I decided t o writ e a book t hat offers a concent rat ed set of " best pract ices" for t he
Oracle PL/ SQL language. The obj ect ive of t his book is t o provide concret e,


im m ediat ely applicable, quickly locat ed advice t hat will assist you in writ ing code t hat
is readable, m aint ainable, and efficient .
You will undoubt edly find recom m endat ions in t his book t hat also appear in som e of
m y ot her books; I hope you will not be offended by t his repet it ion. I t 's sim ply
im possible t o offer in a single book ev eryt hing t hat can and should be writ t en about
t he Oracle PL/ SQL language. While I plan t o reinforce t hese best pract ices in t he
appropriat e places in m y ot her t ext s, I believe t hat we will all benefit from also
having t hem available in one concise book, a book designed, beginning t o end, t o
give you quick access t o m y recom m endat ions for ex cellent PL/ SQL coding
t echniques.

St r u ct u r e of Th is Book
Oracle PL / SQL Best Pract ices is com posed of nine chapt ers and one appendix. Each
chapt er cont ains a set of best pract ices for a part icular area of funct ionalit y in t he
PL/ SQL language. For each best pract ice, I 've provided as m any of t he following
elem ent s as are applicable:
Tit le
A single sent ence t hat describes t he best pract ice and provides an ident ifier
for it in t he form XXX- nn ( where XXX is t he t ype of best pract ice—for exam ple,
EXC for except ion handling —and nn is t he sequent ial num ber wit hin t his set
of best pract ices) ; see Sect ion P.4 for how t o use t his ident ifier online. I have,
whenev er possible, sought t o m ak e t his t it le st and on it s own. I n ot her words,
you should be able t o glance at it and underst and it s im pact on how you writ e
code. This way, aft er y ou've read t he ent ire best pract ice, you can use
Appendix A t o inst ant ly rem ind you of best pract ices as you w rit e y our code.
Descript ion
A lengt hier explanat ion of t he best pract ice. I t 's sim ply not possible t o cov er
all t he nuances in a single sent ence!
Exam ple
We learn best from exam ples, so j ust about ev ery best pract ice illust rat es,
t hrough code and/ or anecdot e, t he value of t he best pract ice. Whenev er it
m akes sense, I put t he exam ple code in a file t hat you can use ( or learn from )
in your own program m ing environm ent . You'll find t hese files on t he O'Reilly
web sit e ( see Sect ion P.4 lat er in t his Preface) .
Benefit s
Why should you bot her wit h t his best pract ice? How crucial is it for you t o
follow t his part icular recom m endat ion? This sect ion offers a quick review of
t he m ain benefit s you w ill see by following t he best pract ice.


Term Fly Presents


Wouldn't it be great if w e lived in a world in which following a best pract ice
was all- around easier t han t he " quick and dirt y" approach? That is,
unfort unat ely, not always t he case. This elem ent warns y ou about t he
challenges, or drawback s, y ou m ight face as you im plem ent t he best pract ice.
I n t he world of t he I nt ernet , everyt hing is connect ed; no program m er st ands
alone! This sect ion recom m ends resources, ranging from books t o URLs t o
files cont aining code, t hat you can use t o help you successfully follow t his
best pract ice. Where filenam es are shown in t his sect ion, t hey refer t o files
available on, or referenced by, t he O'Reilly web sit e.
Here are brief descript ions of t he chapt ers and appendix:
Chapt er 1 st eps back from specific program m ing recom m endat ions. I t offers advice
about how t o im prov e t he overall process by w hich you writ e code.
Chapt er 2 offers a series of suggest ions on how t o form at and organize your code so
t hat it is m ore readable and, t herefore, m ore m aint ainable.
Chapt er 3 t akes a close look at how y ou ought t o declare and m anage dat a wit hin
your PL/ SQL program s.
Chapt er 4 is a " back t o basics" chapt er t hat t alks about t he best way t o writ e I F
st at em ent s, loops, and ev en t he GOTO st at em ent ! Sure, t hese aren't t erribly
com plicat ed const ruct s, but t here are st ill right and wrong ways t o work wit h t hem .
Chapt er 5 cov ers anot her crit ical aspect of robust applicat ion dev elopm ent : ex cept ion
handling, or what t o do when t hings go wrong.
Chapt er 6 focuses on t he m ost crucial aspect of PL/ SQL dev elopm ent : how y ou
should writ e t he SQL st at em ent s in your program s.
Chapt er 7 offers advice on how best t o build your procedures, funct ions, and
t riggers—t he program unit s t hat cont ain your business logic. I t also includes best
pract ices for param et er const ruct ion.
Chapt er 8 st eps back from individual program unit s t o present recom m endat ions for
packages, t he building blocks of any well- designed PL/ SQL- based applicat ion.
Chapt er 9 focuses on how t o t ak e best advant age of a few of t he m ost oft en used of
t he packages provided t o us by Oracle Corporat ion.
Appendix A com piles t he best pract ice t it les across all t he chapt ers int o a concise
resource. Once y ou hav e st udied t he individual best pract ices, y ou can use t his
appendix as a checklist , t o be review ed before you begin coding a new program or
applicat ion.

H ow t o Use Th is Book


My prim ary goal in writ ing t his book was t o creat e a resource t hat w ould m ake a
concret e, not iceable difference in t he qualit y of t he PL/ SQL code y ou w rit e. To
accom plish t his, t he book needs t o be useful and usable not j ust for general st udy,
but also for day- t o- day , program - t o- program t asks. I t also needs t o be concise and
t o t he point . A 1,000- page t ext on best pract ices w ould be ov erwhelm ing,
int im idat ing, and hard t o use.
The result is t his relat ively brief ( I consider any publicat ion under 200 pages a m aj or
personal accom plishm ent ! ) , highly st ruct ured book . I recom m end t hat you approach
Oracle PL/ SQL Best Pract ices as follows:
1. Read Sect ion P.3. Som e of t he best pract ices in t his book—whole chapt ers, in
fact —will have a m uch higher im pact t han ot hers on t he qualit y and efficiency
of your code. I f you find t hat your current pract ices ( or t hose of y our
organizat ion) are far from t he m ark, t hen y ou w ill have ident ified your
priorit ies for init ial st udy.
2. Skip t o Appendix A and peruse t he best pract ice t it les from each chapt er. I f
you hav e been program m ing for any lengt h of t im e, you will probably find
yourself t hinking: " Yes, I do t hat ," and " Uh- huh, we'v e got t hat one cov ered."
Great ! I w ould st ill encourage y ou t o read what I 've got t o say on t hose t opics,
as y ou m ight be able t o deepen y our knowledge or learn new t echniques. I n
any case, a quick review of t he appendix will allow you t o ident ify areas t hat
are new t o y ou, or perhaps st rike a chord, as in " Oh m y gosh, t hat program I
wrot e last week does ex act ly what St even say s t o av oid. Bet t er check t hat
out ! "
3. Dive int o individual chapt ers or best pract ices wit hin chapt ers. Read a best
pract ice, wrest le wit h it , if necessary, t o m ake sure t hat y ou really, t ruly
agree wit h it . And t hen apply t hat best pract ice. This isn't an academ ic
ex ercise. You will only t ruly absorb t he lesson if you apply it t o your code—if
you hav e a problem or program t hat can be im prov ed by t he best pract ice.
I f y ou are new t o program m ing or new t o PL/ SQL, y ou will cert ainly also benefit
great ly from a cov er- t o- cov er reading of t he t ex t . I n t his case, don't t ry t o fully
absorb and t est out ev ery best pract ice. I nst ead, read and t hink about t he best
pract ices wit hout t he pressure of applying each one. When you are done, t ry t o
pict ure t he best pract ices as a whole, reinforcing t he following t hem es:

I want t o w rit e code t hat I —and ot hers—can easily underst and and change as
The w orld is t erribly com plex, so I should st rive t o k eep m y code sim ple. I can
t hen m eet t hat com plexit y t hrough carefully designed int eract ion bet ween
elem ent s of m y code.

Then y ou will be ready t o go back t o individual chapt ers and deepen your
underst anding of individual best pract ices.
The ot her crucial way t o t ake advant age of t his book is t o use t he code provided on
t he com panion web sit e. See Sect ion P.4 for det ailed inform at ion on t he soft ware
t hat will help you bring your best pract ices t o life.

N ot All Be st Pr act ice s Ar e Cr e a t e d Equ al


Term Fly Presents


This book cont ains about 120 dist inct recom m endat ions. I could have included m any,
m any m ore. I n fact , I filled up a Rej ect s docum ent as I wrot e t he book. Following t he
prov en, " t op- down" approach, I first cam e up w it h a list of best pract ices in each
area of t he language. Then I w ent t hrough each area, filling in t he descript ions,
exam ples, and so on. As I did t his, I encount ered num erous " best pract ices" t hat
surely w ere t he right way t o do t hings. The realit y, how ev er, is t hat few people
would ever bot her t o rem em ber and follow t hem , and if t hey did bot her, it would not
m ake a significant difference in t heir code.
I had realized, you see, t hat not all best pract ices are creat ed equal. Som e are m uch,
m uch m ore im port ant t han ot hers. And som e are j ust bet t er left out of t he book, so
t hat readers aren't dist ract ed by " clut t er." I hope t hat t he result —t his book—has an
im m ediat e and last ing im pact . But ev en am ong t he best pract ices I didn't rej ect ,
som e st and out as being especially im port ant —so I 'v e decided t o award t hese best
pract ices t he following prizes:
Grand Prize
SQL- 00: Est ablish and follow clear rules for how t o w rit e SQL in your
applicat ion. ( See Chapt er 6.)
First Prize
MOD- 01: Encapsulat e and nam e business rules and form ulas behind funct ion
headers. ( See Chapt er 7 .)
Second Prize: Tw o Winners
EXC- 00: Set guidelines for applicat ion- wide error handling before you st art
coding. ( See Chapt er 5.)
PKG- 02: Provide w ell- defined int erfaces t o business dat a and funct ional
m anipulat ion using packages. ( See Chapt er 8 .)
Third Prize: Four Winners
MOD- 03: Lim it execut ion sect ion sizes t o a single page using m odularizat ion.
( See Chapt er 7.)
DAT- 15: Expose package globals using " get and set " m odules. ( See Chapt er
DEV- 03: Walk t hrough each ot her's code. ( See Chapt er 1.)
STYL- 09: Com m ent t ersely wit h value- added inform at ion. ( See Chapt er 2 .)
I f y ou follow each of t hese " best of t he best " pract ices, you will end up wit h
applicat ions t hat are t he j oy and envy of developers every where!

Abou t t h e Code


The best way t o learn how t o w rit e good code is by analyzing and following exam ples.
Alm ost ev ery best pract ice offered in t his book includes a code exam ple, bot h in t he
t ext and in downloadable form from t he Oracle PL/ SQL Best Pract ices sit e, av ailable
t hrough t he O'Reilly & Associat es sit e at :
ht t p: / / www.oreilly.com / cat alog/ orbest prac
To locat e t he code for y our best pract ice, sim ply ent er t he best pract ice ident ifier,
such as BI P- 1 0 , in t he search field. You will t hen be direct ed t o t he associat ed code.
You can also browse t he sit e by t opic area. You can ev en offer y our own insight s
about PL/ SQL best pract ices, so I encourage you t o visit and cont ribut e.
As a rule, I will follow m y own best pract ices in t hese exam ples ( unless t he point of
t he code is t o dem onst rat e a " bad pract ice" ! ) . So, for exam ple, y ou will rarely see
m e using DBMS_OUTPUT.PUT_LI NE, ev en t hough t his " show m e" capabilit y is needed
in m any program s. As I m ent ion in [ BI P- 01: Av oid using t he
DBMS_OUTPUT.PUT_LI NE procedure direct ly.] , you should avoid calling t his
procedure direct ly; inst ead, build or use an encapsulat ion over
DBMS_OUTPUT.PUT_LI NE. So rat her t han seeing code like t his:
DBMS_OUTPUT.PUT_LINE (l_date_published);
you will inst ead encount er a call t o t he " pl" or " put line" procedure:
pl (l_date_published);
I also m ak e m any references t o PL/ Vision packages. PL/ Vision is a code library,
consist ing of m ore t han 60 packages t hat offer 1,000- plus procedures and funct ions
t o perform a m y riad of useful t asks in PL/ SQL applicat ions. I have deposit ed m uch of
what I have learned in t he last five y ears about PL/ SQL int o PL/ Vision, so I nat urally
ret urn t o it for exam ples. Any package m ent ioned in t his book whose nam e st art s
wit h " PLV" is a PL/ Vision package.
A com plet ely free, " lit e" version of PL/ Vision is available from t he PL/ SQL Pipeline
Archives at :
ht t p: / / www.rev ealnet .com / Pipelines/ PLSQL/ archives.ht m
Select t he " Rev ealNet Act ive PL/ SQL Knowledge Base" from t he list . ( You m ight also
like t o download and t ry out t he ot her code y ou'll find t here.) A com m ercial version
of PL/ Vision ( wit h m ore packages and funct ionalit y t han t he lit e version) is current ly
available inside t he Rev ealNet Act ive PL/ SQL Knowledge Base
( ht t p: / / www.rev ealnet .com / ) .
Whenev er possible, t he code I provide for t he book can be used t o generat e best pract ice- based code and as prebuilt , generalized com ponent s in your applicat ions,
code t hat y ou can use w it hout having t o m ake any m odificat ions.
The code exam ples offer program s t hat y ou can use t o bot h generat e and direct ly
im plem ent t hose best pract ices. I n som e cases, t he program s are rat her sim ple


Term Fly Presents


" prot ot ypes" ; t hey w ork as adv ert ised, but y ou will probably want t o m ake som e
changes before you put t hem int o product ion applicat ions.
And you should m ost cert ainly t est every single program y ou use from Oracle PL
/ SQL Best Pract ices ! I have run som e t est s, and m y w onderful t echnical reviewers
have also ex ercised t he code. I n t he end, how ev er, if t he code goes int o your
applicat ion, you are responsible for m aking sure t hat it m eet s y our needs.

Ot h e r Re sou r ces
This book is int ended t o com plem ent num erous ot her resources for PL/ SQL
dev elopers. I t is, t o m y knowledge, t he first collect ion of best pract ices specifically
for t he Oracle PL/ SQL language. On t he ot her hand, it doesn't st and on it s own as a
com prehensive resource, eit her for PL/ SQL, in part icular, or for Oracle applicat ion
dev elopm ent , in general.
What follows is by no m eans an exhaust ive list of resources for dev elopers. However,
I find t hat a 15- page bibliography is m ore int im idat ing t han it is helpful. So I offer
t his short list of t he resources t hat I hav e recent ly found m ost useful and int erest ing:
Code Com plet e by St ev en McConnell ( Microsoft Press)
A classic t ext , t his " pract ical handbook of soft w are crit icism " should be on t he
book shelf of every developer or at least in your t eam 's library. Chock- full of
pract ical advice for const ruct ing code, it show s exam ples in m any languages,
including Ada, which is enough like PL/ SQL t o m ake learning from McConnell a
breeze. Don't st art coding wit hout it ! The web sit e for St ev en McConnell's
consult ing pract ice, ht t p: / / www.const rux.com / , is also packed wit h lot s of
good advice.
Refact oring by Mart in Fowler ( Addison Wesley)
According t o t his book, " refact oring is t he process of changing a soft ware
syst em in such a way t hat it doesn't alt er t he ex t ernal of t he code, y et
im proves it s int ernal st ruct ure." Sound great , or what ? This ex cellent book
uses Java as it s exam ple language, but t he w rit ing is clear and t he Java
st raight forward. There is m uch t o apply here t o PL/ SQL program m ing.
Ext rem e Program m ing Explained, by Kent Beck ( Addison Wesley)
This book is a highly readable and concise int roduct ion t o Ext rem e
Program m ing ( XP) , a light weight soft ware dev elopm ent m et hodology. Visit
ht t p: / / www.xprogram m ing.com / or ht t p: / / www.ext rem eprogram m ing.org/
for a glim pse int o t he world of t his int erest ing approach t o dev elopm ent .
And t hen, of course, t here is m y own oeuvre, t he Oracle PL/ SQL Series from O'Reilly
& Associat es, which includes:
Oracle PL/ SQL Program m ing, wit h Bill Pribyl


The com plet e language reference for Oracle PL/ SQL.
Oracle PL/ SQL Program m ing: Guide t o Oracle8i Feat ures
A com panion volum e describing t he Oracle8i addit ions t o t he PL/ SQL language.
Oracle PL/ SQL Dev eloper's Workbook, wit h Andrew Odewahn
A workbook cont aining problem s ( and accom panying solut ions) t hat will t est
your knowledge of Oracle PL/ SQL language feat ures.
Oracle Built - in Packages, wit h Charles Dy e and John Beresniewicz
A com plet e reference t o t he m any built - in packages provided by Oracle
Corporat ion.
Advanced Oracle PL/ SQL Program m ing wit h Packages
A descript ion of how t o writ e your own PL/ SQL packages, including a large
num ber of packages you can use in your own program s.
Oracle PL/ SQL Language Pocket Reference, wit h Bill Pribyl and Chip Dawes
A quick reference t o t he PL/ SQL language synt ax.
Oracle PL/ SQL Built - ins Pocket Reference, wit h John Beresniewicz and Chip Dawes
A quick reference t o t he calls t o t he Oracle built - in funct ions and packages.

Con ven t ion s Use d in Th is Book
The following t ypographical convent ions are used in t his book:
I t alic
I ndicat es filenam es, direct ory nam es, and URLs. I t 's also used for em phasis
and for t he first use of a t echnical t erm .
Used when referring, by num ber, t o a best pract ice described in t his book
( e.g., [ BI P- 04: Handle expect ed and nam ed except ions when perform ing file
I / O.] ) .
Const ant widt h
I ndicat es exam ples and t o show t he cont ent s of files and t he out put of
com m ands.


Term Fly Presents


Constant width bold
I ndicat es code ent ered by a user ( e.g., via SQL* Plus) or t o highlight code
lines being discussed.
I n code exam ples, indicat es PL/ SQL k eyw ords.
I n code exam ples, indicat es user- defined it em s ( e.g., variables) .

This icon designat es a not e, which is an im port ant
aside t o t he nearby t ext . For exam ple, I 'll use t his icon
when suggest ing t he use of an alt ernat ive feat ure.
This icon designat es a warning relat ing t o t he nearby
t ext . For exam ple, I 'll use t his icon when a part icular
feat ure m ight affect perform ance or preclude use of
som e ot her feat ure.

Com m e n t s an d Qu est ion s
Please address com m ent s and quest ions concerning t his book t o t he publisher:
O'Reilly & Associat es, I nc.
101 Morris St reet
Sebast opol, CA 95472
( 800) 998- 9938 ( in t he Unit ed St at es or Canada)
( 707) 829- 0515 ( int ernat ional/ local)
( 707) 829- 0104 ( fax)
There is a w eb page for t his book, which list s errat a, exam ples, or any addit ional
inform at ion. You can access t his page at :
ht t p: / / www.oreilly.com / cat alog/ orbest prac
To com m ent or ask t echnical quest ions about t his book, send em ail t o:
bookquest ions@oreilly.com
For m ore inform at ion about books, conferences, soft ware, Resource Cent ers, and t he
O'Reilly Net work , see t he O'Reilly web sit e at :
ht t p: / / www.oreilly.com /

Ack n ow ledgm en t s

Thanks go, first of all, t o m y edit or of six years at O'Reilly & Associat es, Deborah
Russell. She got m e off t he dim e on t his proj ect and helped m e t urn it around in
record t im e ( I st art ed doing serious w rit ing on t his book in Oct ober 2000 and finished
it up in January 2001) . I t was, once again, a real pleasure working wit h you, Debby!
Thanks as w ell t o t he ot her O'Reilly people who t urned t his book int o a finished
product : Mary Anne Weeks May o, t he product ion edit or; Ellie Volckhausen, who
designed t he cov er; and Caroline Senay, t he edit orial assist ant who helped in m any
ways t hroughout t he proj ect .
Many out st anding Oracle developers and DBAs cont ribut ed t heir t im e and expert ise,
t hrough t echnical review, code sam ples, or w rit ing. My deep- felt grat it ude goes out
t o: John Beresniewicz, Rohan Bishop, Dick Bolz, Dan Clam age, Bill Caulkins, Dan
Condon- Jones, Fawwad- uz- Zafar Siddiqi, Gerard Hart gers, Edwin van Hat t em ,
Dwayne King, Darryl Hurley, Giovanni Jaram illo, Vadim Loev ski, Pav el Luzanov,
Mat t hew MacFarland, Jeffrey Meens, Jam es " Padders" Padfield, Rakesh Pat el, Bill
Pribyl, Andre Vergison ( t he brains behind PL/ Form at t er) , and Solom on Yakobson.
This book benefit ed, in part icular, from a rew orking of best pract ice t it les by John
Beresniewicz, close readings of m any chapt ers by Dan Clam age ( whose ex cellent
com m ent s on cert ain best pract ices I 've included as sidebars in t he t ext ) , and t he
cont ribut ion of t rigger best pract ices by Darryl Hurley.
Oracle PL/ SQL Best Pract ices is a m uch im prov ed t ext as a result of all of your
assist ance, m y friends. Any errors, on t he hand, are ent irely m y fault and
responsibilit y.
I would also like t o t hank m y wife, Veva, for volunt eering t o pick up Eli from Jordan's
house so t hat I could st ay behind and writ e t hese acknowledgm ent s ( oh, and also for
adding layer upon layer of m eaning and happiness t o m y life) .

Ch a pt e r 1 . Th e D e ve lopm e n t Pr oce ss
To do y our j ob w ell, you need t o be aware of, and t o follow, bot h " lit t le" best
pract ices—very focused t ips on a part icular coding t echnique—and " big" best
pract ices. This chapt er offers som e suggest ions on t he big pict ure: how t o w rit e your
code as part of a high- qualit y dev elopm ent process.
My obj ect ive isn't t o " sell" you on any part icular dev elopm ent m et hodology ( t hough I
m ust adm it t hat I am m ost at t ract ed t o so- called " light weight " m et hodologies such
as Ext rem e Program m ing and SCRUM) . [ 1] I nst ead, I 'll rem ind you of basic processes
you should follow wit hin any big- pict ure m et hodology.
[ 1]
This chapt er cont ains num erous references t o Ext rem e Program m ing resources. For m ore
inform at ion about SCRUM, " a process for em pirically m anaging product developm ent and
im proving t eam product ivit y," visit ht t p: / / www.cont rolchaos.com / . Not e t hat SCRUM isn't an
acronym , but a reference t o t he " scrum " in t he sport of rugby, a m et aphor for t he daily
m eet ings t hat are t he core of t he SCRUM m et hodology.


Term Fly Presents


I n ot her w ords, if you ( or your m et hodology) don't follow som e form of t he best
pract ices in t his chapt er, y ou are less likely t o produce high- qualit y, successful
soft ware. I don't ( wit h perhaps a single except ion) suggest a specific pat h or t ool.
You j ust need t o m ak e sure you've got t hese bases cov ered.

D EV- 0 1 : Se t st an da r ds an d gu ide lin e s be fore
w r it in g an y code .

These st andards and guidelines would, if I had m y way , include m any or all of t he
best pract ices described in t his book. Of course, you need t o m ake your own
decisions about what is m ost im port ant and pract ical in your own part icular
environm ent .
Key areas of dev elopm ent for which you should proact ively set st andards are:

Select ion of dev elopm ent t ools : You should no longer be relying on SQL* Plus
t o com pile, execut e, and t est code; on a basic edit or like Not epad t o w rit e t he
code; or on EXPLAI N PLAN t o analyze applicat ion perform ance. Soft ware
com panies offer a m ult it ude of t ools ( wit h a wide range of funct ionalit y and
price) t hat will help dram at ically im prove y our dev elopm ent environm ent .
Decide on t he t ools t o be used by all m em bers of t he developm ent group.

How SQL is writ t en in PL/ SQL code : The SQL in your applicat ion can be t he
Achilles' heel of y our code base. I f you aren't careful about how y ou place
SQL st at em ent s in your PL/ SQL code, y ou'll end up wit h applicat ions t hat are
difficult t o opt im ize, debug, and m anage ov er t im e.

An except ion handling archit ect ure : Users hav e a hard t im e underst anding
how t o use an applicat ion correct ly, and developers hav e an ev en harder t im e
debugging and fixing an applicat ion if errors are handled inconsist ent ly ( or not
at all) . The best way t o im plem ent applicat ion- wide, consist ent error handling
is t o use a st andardized package according t o specific guidelines.

Processes for code review and t est ing : There are som e basic t enet s of
program m ing t hat m ust not be ignored. You should never put code int o
product ion wit hout having it reviewed by one or m ore ot her developers, and
wit hout perform ing exhaust ive t est ing. Ast onishingly, m any ( if not m ost )
PL/ SQL developm ent shops hav e neit her st andard, m andat ory code reviews
nor a st rict t est ing regim en.

Best pract ices t hroughout t his chapt er and t he rest of t he book address t hese crucial
aspect s of soft ware dev elopm ent . You will also find m any relevant exam ples
t hroughout t he book.

Be n e fit s
By set t ing clear st andards and guidelines for at least t he areas j ust list ed ( t ools, SQL,
error handling, and code review and t est ing) , y ou ensure a foundat ion t hat will allow
you t o be product ive and t o produce code of reasonable qualit y.


Ch a lle n ge s
The deadline pressures of m ost applicat ions m it igat e against t aking t he t im e up front
t o est ablish st andards, ev en t hough we all know t hat such st andards are likely t o
save t im e down t he line.

D EV- 0 2 : Ask for h e lp a ft er 3 0 m in u t es on a
pr oblem .

Following t his sim ple piece of advice will probably have m ore im pact on your code
t han anyt hing else in t his book!
How m any t im es hav e y ou st ared at t he screen for hours, t rying t his and t hat
vain at t em pt t o fix a problem in your code? Finally, exhaust ed and desperat e,
call over y our cubicle wall: " Hey, Melinda, could you com e ov er here and look
t his?" When Melinda reaches your cube she sees in an inst ant what you, aft er
st ill could not see. Gosh, it 's like m agic!

in a

Except it 's not m agic and it 's not m yst erious at all. Rem em ber: hum ans writ e
soft ware, so an underst anding of hum an psychology is crucial t o set t ing up processes
t hat encourage qualit y soft ware. We hum ans ( especially t he m ales of t he species)
like t o get t hings right , like t o solve our own problem s, and do not like t o adm it t hat
we don't know what is going on. Consequent ly, we t end t o want t o hide our
ignorance and difficult ies. This t endency leads t o m any wast ed hours, high levels of
frust rat ion, and, usually, nast y, spaghet t i code.
Team leaders and developm ent m anagers need t o cult ivat e an environm ent in which
we are encouraged t o adm it what we do not know, and ask for help earlier rat her
t han lat er. I gnorance isn't a problem unless it is hidden from view. And by asking for
help, you validat e t he knowledge and experience of ot hers, building t he ov erall selfest eem and confidence of t he t eam .
There is a good chance t hat if you spend 30 m inut es fruit lessly analyzing your code,
t wo m ore hours will not get y ou any furt her along t o a solut ion. I nst ead, get in t he
habit of sharing your difficult y wit h a cow orker ( preferably an assigned " buddy," so
t he line of com m unicat ion bet w een t he t w o of y ou is officially acknowledged and
doesn't represent in any way acknowledgem ent of a failure) .

Ex a m ple
Program m ers are a proud and noble people. We don't like t o ask for help; we like t o
bury our noses in our screen and creat e. So t he biggest challenge t o get t ing people
t o ask for help is t o change behaviors. Here are som e suggest ions:


The t eam leader m ust set t he exam ple. When I have t he privilege t o m anage
a t eam of dev elopers, I go out of m y way t o ask each and ev ery person on
t hat t eam for help on one issue or anot her. I f y ou are a coach t o ot her t eam s
of dev elopers, ident ify t he program m er who is respect ed by all ot hers for her

Term Fly Presents


expert ise. Then convince her t o seek out t he advice of ot hers. Once t he leader
( form al or inform al) shows t hat it is OK t o adm it ignorance, ev ery one else will
gladly j oin in.

Post rem inders in work areas, perhaps ev en individual cubicles, such as
need t o be rem inded about t hings t hat don't com e nat urally t o us.

Be n e fit s
Problem s in code are ident ified and solved m ore rapidly. Fewer hours are wast ed in a
fut ile hunt for bugs.
Knowledge about t he applicat ion and about t he underlying soft ware t echnology is
shared m ore evenly across t he dev elopm ent t eam .

Ch a lle n ge s
The m ain challenge t o successful im plem ent at ion of t his best pract ice is psychological:
don't be afraid t o adm it you don't know som et hing or are having t rouble figuring
som et hing out .

Re sou r ce s
Peopleware : Product iv e Proj ect s and Team s, by Tom DeMarco and Tim ot hy List er
( Dorset House) . This is a fant ast ic book t hat com bines deep experience in proj ect
m anagem ent wit h hum or and com m on sense.

D EV- 0 3 : W alk t h r ou gh e a ch ot h e r's code .

Soft ware is w rit t en t o be ex ecut ed by a m achine. These m achines are very, very fast ,
but t hey aren't t erribly sm art . They sim ply do what t hey are t old, following t he
inst ruct ions of t he soft w are we writ e, as w ell as t he m any ot her layers of soft ware
t hat cont rol t he CPU, st orage, m em ory, et c.
I t is ext rem ely im port ant , t herefore, t hat we m ake sure t he code we writ e does t he
right t hing. Our com put ers can't t ell us if we m issed t he m ark ( " garbage in, garbage
out " or, unfort unat ely, " garbage in, gospel out " ) . The usual way we validat e code is
by running t hat code and checking t he out com es ( well, act ually, in m ost cases we
have our users run t he code and let us know about failures) . Such t est s are, of
course, crucial and m ust be m ade. But t hey aren't enough.
I t is cert ainly possible t hat our t est s aren't com prehensive and leave errors
undet ect ed. I t is also conceivable t hat t he way in which our code was w rit t en
produces t he correct result s in very undesirable ways. For inst ance, t he code m ight
work " by accident " ( t wo errors cancel t hem selves out ) .


A crucial com plem ent t o form al t est ing of code is a form alized process of code review
or walk- t hrough. Code review involves having ot her dev elopers act ually read and
review your source code. This review process can t ake m any different form s,

The buddy syst em : Each program m er is assigned anot her program m er t o be
ready at any t im e t o look at his buddy's code and t o offer feedback.

Form al code walkt hroughs : On a regular basis ( and cert ainly as a " gat e"
before any program m oves t o product ion st at us) , a developer present s or
" walks t hrough" her code before a group of program m ers.

Pair program m ing : No one codes alone! Whenev er you writ e soft ware, y ou
do it in pairs, where one person handles t he t act ical work ( t hinks about t he
specific code t o be writ t en and does t he t yping) , while t he second person
t akes t he st rat egic role ( keeps an ey e on t he ov erall archit ect ure, looks out
for possible bugs, and generally crit iques—always const ruct ively) . Pair
program m ing is an int egral part of Ext rem e Program m ing.

Be n e fit s
Ov erall qualit y of code increases dram at ically. The archit ect ure of t he applicat ion
t ends t o be sounder, and t he num ber of bugs in product ion code goes w ay down. A
furt her advant age is t hat of st aff educat ion —not j ust awareness of t he proj ect , but
also an increase in t echnological proficiency due t o t he synergist ic effect of w orking
t oget her.

Ch a lle n ge s
The dev elopm ent m anager or t eam leader m ust t ake t he init iat ive t o set up t he code
review process and m ust give dev elopers t he t im e ( and t raining) t o do it right . Also,
code review seem s t o be t he first casualt y of deadline crunch. Furt her, a new PL/ SQL
proj ect m ight not have t he language expert ise available on t he t eam t o do com plet e,
m eaningful walkt hroughs.

Re sou r ce s
1. Handbook of Walkt hroughs, I nspect ions, and Technical Reviews, by Daniel
Freedm an and Gerald M. Weinberg ( Dorset House) . Now in it s t hird edit ion,
t his book uses a quest ion- and- answer form at t o show you exact ly how t o
im plem ent review s for all sort s of product and soft ware dev elopm ent .
2. Ext rem e Program m ing Explained, by Kent Beck ( Addison Wesley) . The first
book on Ext rem e Program m ing offers m any insight s int o pair program m ing.
3. Ext rem e Program m ing I nst alled, by Ron Jeffries, Ann Anderson, and Chet
Hendrickson ( Addison Wesley) . Focuses on how t o im plem ent Ext rem e
Program m ing in your environm ent .

D EV- 0 4 : Valida t e st an da r ds a gain st sou r ce code
in t h e da t a ba se .


Term Fly Presents


This book is chock- full of recom m endat ions, st andards, guidelines, and so on. The
usual im m ediat e, visceral response t o all of t hese shoulds is: how can I possibly
rem em ber t hem ? And how can I m ak e sure t hat any of our developers act ually follow
t hrough on t heir " shoulds?"
PL/ SQL offers one big advant age in t his area: all source code is st ored in t he
dat abase and is m ade available t hrough dat a dict ionary views ( ALL_SOURCE,
USER_SOURCE, DBA_SOURCE) . Oracle also m aint ains addit ional inform at ion about
code, such as dependencies, in ot her views. You can—and should—fairly easily
validat e at least som e of t he st andards t hat y ou set by running queries against t hese
Here are som e t hings y ou can do wit h t his inform at ion:

Set up a w eekly j ob ( via DBMS_ JOB) t o ident ify any program s t hat hav e
changed, hav e been creat ed, or have been rem ov ed in t he past w eek. Publish
t his inform at ion as HTML on an int ranet so dev elopers can, at any t im e, be
aware of t hese changes. This approach can im prov e reuse wit hin your
organizat ion, for exam ple.

Provide queries, preferably organized wit hin program s in a package, t hat
dev elopers can run ( or, again, can be run as scheduled, weekly j obs) t o check
t o see how well t heir code com plies wit h st andards.

Execut ing, as well as writ ing, queries against dat a
dict ionary views ( part icular ly t he dependency- relat ed
views) can be t im e- consum ing. Be pat ient !
Ex a m ple
Suppose we have agreed t hat individual developers should never call
RAI SE_APPLI CATI ON_ERROR direct ly. I nst ead t hey should call t he raise procedure of
t he st andard error- handling package ( see [ EXC- 04: Use your own raise procedure in
place of explicit calls t o RAI SE_APPLI CATI ON_ERROR.] ) .
Here is a sim ple query t hat ident ifies all t hose program unit s ( and lines of code) t hat
cont ain t his " off lim it s" built - in:

name, line || ' - ' || text code
BY name, line;

This answers a com m on quest ion: " does m y code hav e X in it ?" Rat her t han
ex ecut ing t hese st andalone queries ov er and ov er again, you will find it wort hwhile t o
encapsulat e such a query inside a pack aged int erface, such as t his " st andards
validat ion" package:


PROCEDURE progwith (str IN VARCHAR2);
END valstd;
You can now call valst d.pw_rae t o show all t he " program s wit h"
RAI SE_APPLI CATI ON_ERROR ( as you can easily see from t he valst d package body) .
You can also call valst d.progwit h t o search for ot her st rings. I f, t herefore, You've a
st andard t hat dev elopers should nev er hard- code - 20,000 error num bers, issue t his
com m and:
SQL> exec valstd.progwith ('-20')
and view what is likely t o be a superset of all such inst ances.
Anot her kind of st andard t hat m ight be set wit hin an organizat ion is t hat applicat ion
code should never reference a t able or view direct ly but inst ead always go t hrough
an encapsulat ion package ( [ SQL- 01: Qualify PL/ SQL variables wit h t heir scope nam es
when referenced inside SQL st at em ent s. ] ) . Here is a query t hat ident ifies all program
unit s t hat violat e t his rule:
SELECT owner || '.' || name refs_table,
referenced_owner || '.' ||
referenced_name table_referenced
FROM all_dependencies
WHERE owner LIKE UPPER ('&1')
AND referenced_type IN ('TABLE', 'VIEW')
ORDER BY owner,

Be n e fit s
You don't have t o rely solely on " m anual" walkt hroughs of code t o validat e
com pliance wit h group st andards.
Code analysis and code " m ining" ( ext ract ing inform at ion from / about source code)
can be aut om at ed and t ight ly int egrat ed int o t he developm ent process.

Ch a lle n ge s
You need t o design and build t he analysis code and t hen int egrat e t hese check s int o
your ongoing dev elopm ent effort .

Re sou r ce s


Term Fly Presents


1. reft abs.sql : Query ident ifying direct references t o t ables and view s.
2. valst d.pkg : Sim ple prot ot ype package offering an int erface t o ident ify t he
presence of unwant ed t ext in source code.

D EV- 0 5 : Gen e r at e code w h en e ve r possible an d
a ppr opr ia t e.
Life is short —and way t oo m uch of it is consum ed by t im e spent in front of a
com put er screen, m oving digit s wit h varying accuracy ov er t he keyboard. Seem s t o
m e t hat w e should be aggressive about finding ways t o build our applicat ions wit h an
absolut e m inim um of t im e and effort while st ill producing qualit y goods. A k ey
com ponent of such a st rat egy is code generat ion: rat her t han writ e t he code yourself,
you let som e ot her piece of soft w are w rit e t he code for you.
Code generat ion is part icularly useful when you have defined st andards you want
ev ery one t o follow. You can t ry t o get dev elopers t o conform t o t hose st andards wit h
a " st ick" approach: follow t he st andards, or else! But a m ore effect ive w ay t o get t he
oft en anarchist ic, or at least highly individualist ic, program m er t o follow st andards is
t o m ak e it easier t o follow t han not follow t hose guidelines. See Exam ples for specific
dem onst rat ions of t his " carrot " approach.
I n addit ion t o helping t o im plem ent st andards, code generat ion com es in handy when
you hav e t o writ e code t hat is repet it ive in st ruct ure ( i.e., it can be expressed
generally by a pat t ern) . For exam ple, t he kind of code y ou w rit e t o det erm ine if t here
is at least one row in a t able for a given prim ary key is t he sam e regardless of t he
t able ( and prim ary key) . Wouldn't it be nice t o be able t o call a procedure t hat
queries t he t able st ruct ure and key from t he dat a dict ionary and generat es t he
funct ion?
How do you generat e code? You can pick from one of t hese t hree opt ions:

Writ e y our own cust om query or program t o m eet specific needs. Exam ples
st eps you t hrough a sim ple dem onst rat ion of how t o go about t his.

Use a com m ercial t ool t hat focuses on code generat ion. Resources offers a list
of known code- generat ion t ools for PL/ SQL dev elopers.

Run relat ively const rained, funct ionally specific generat ion ut ilit ies t hat ot hers
have w rit t en ( noncom m ercial, freeware) . Resources offers a list of generat ion
ut ilit ies available on t he Oracle PL/ SQL Best Pract ices w eb sit e.

Ex a m ple s
Let 's explore t hese t hree opt ions for generat ion.
First , we hav e t he classic " SQL generat ing SQL." Suppose t hat I want t o drop all t he
t ables in m y schem a. There is no " drop all" com m and. I nst ead, I t hrow t oget her a


query against USER_TABLES whose out put is, in fact , a series of DROP st at em ent s,
and t hen ex ecut e t hat out put as a spooled file in SQL* Plus:
SELECT 'DROP TABLE ' || table_name || ';'
FROM user_tables
WHERE table_name LIKE UPPER ('&1%')
SPOOL drop.cmd
Now, let 's m ov e on t o PL/ SQL- based generat ion. My t eam is about t o st art a largescale developm ent effort . We will need t o perform ret rievals of ent ire rows of dat a for
m any different t ables, based on t heir various ( but single) prim ary key colum ns. I
want t o do t his in a way t hat conform s t o all of our organizat ion's st andards
( except ion handling wit h logging, use, and encapsulat ion of t he im plicit query t hat
offers best perform ance, et c.) . Rat her t han w rit e a m em o t o t his effect , I build a
VARCHAR2 (100) := LOWER (tab);
VARCHAR2 (100) := LOWER (col);
pl ('CREATE OR REPLACE FUNCTION ' || l_ltab || '_row_for (');
pl ('
' ||
l_lcol || '_in IN ' || l_ltab || '.' || l_lcol || '%TYPE)');
pl ('
RETURN ' || l_ltab || '%ROWTYPE');
pl ('IS');
pl ('
retval ' || l_ltab || '%ROWTYPE;');
pl ('BEGIN');
pl ('
SELECT * INTO retval');
pl ('
FROM ' || l_ltab);
pl ('
WHERE ' || l_lcol || ' = ' || l_lcol || '_in;');
pl ('
RETURN retval;');
pl ('
pl ('
pl ('
pl ('
pl ('END ' || l_ltab || '_row_for;');
pl ('/');
And I can t hen use t his procedure as follows:
SQL> exec genlookup ('book', 'isbn')
isbn_in IN book.isbn%TYPE)


Term Fly Presents


retval book%ROWTYPE;
SELECT * INTO retval
FROM book
WHERE isbn = isbn_in;
RETURN retval;
END book_row_for;
You can get m uch m ore sophist icat ed in your generat ion effort s; y ou can, for
exam ple, look up t he prim ary key colum n( s) in t he ALL_CONS_COLUMNS dat a
dict ionary view, inst ead of having t o specify t he WHERE clause colum n. You hav e t o
decide for yourself where t o draw t he line: do y ou really need t hat flexibilit y or does
it j ust look like lot s of fun t o build?

Be n e fit s
You can build your applicat ions fast er; ut ilit ies can generat e soft ware lot s fast er t han
you can t ype it .
You will im prove t he qualit y of your applicat ion code: assum ing t hat your generat or
program has been w ell- designed and t est ed, it will generat e bug- free code wit h each
As y our underlying dat a st ruct ures change, y ou can regenerat e program unit s t hat
work wit h t hose dat a st ruct ures. Much less t im e is spent upgrading exist ing code.

Ch a lle n ge s
Building anyt hing but t he m ost crude generat ors involves a lev el of abst ract ion and
com plexit y higher t han t he usual t ask t ackled by m ost developers.

Re sou r ce s
Com m e r cia l Code - Ge n e r a t ion Tools
1. ht t p: / / www.oracle.com / : Oracle Designer from Oracle Corporat ion generat es
code in a variet y of languages.
2. ht t p: / / www.rev ealnet .com / : RevealNet 's PL/ Generat or generat es
com prehensive encapsulat ion packages for t ables and views.
3. PLVgen: RevealNet 's Act ive PL/ SQL Knowledge Base offers PLVgen, a package
t hat generat es funct ions, procedures, cursor FOR loops and ot her code
elem ent s. Visit t he PL/ SQL Pipeline archives as described in t he Preface.
4. Most CASE/ designer t ools offer som e lev el of code generat ion. Visit t he web
sit es of Quest , Com put er Associat es, Precise, BMC, Em barcadero, and so on
t o check out t heir respect ive product s.


Code - Ge n e r a t ion Ut ilit ie s
1. genlookup.pro : Generat es a lookup procedure t hat ret urns a row in a t able.
2. m sginfo.pkg : Generat es a package wit h definit ions for all applicat ion- specific
except ions.
3. genm ods.pkg : Generat es st andard form at t ed funct ions.

D EV- 0 6 : Se t u p a n d u se form a l u n it t e st in g
pr oce du r e s.

A unit t est is a t est a developer creat es t o ensure t hat his or her " unit ," usually a
single program , w orks properly. A unit t est is very different from a sy st em or
funct ional t est ; t hese lat t er t ypes of t est s are orient ed t o applicat ion feat ures or
ov erall t est ing of t he sy st em . You can't properly or effect ively perform a sy st em t est
unt il you know t hat t he individual program s behave as expect ed.
So, of course, you w ould t herefore expect t hat program m ers do lot s of unit t est ing
and have a correspondingly high level of confidence in t heir program s. Ah, if only
t hat were t he case! The realit y is t hat program m ers generally perform an inadequat e
num ber of inadequat e t est s and figure t hat if t he users don't find a bug, t here is no
bug. Why does t his happen? Let m e count t he ways:
The psychology of success and failure
We are so focused on get t ing our code t o w ork correct ly t hat we generally shy
away from bad news, from ev en want ing t o t ake t he chance of get t ing bad
news. Bet t er t o do som e cursory t est ing, confirm t hat it seem s t o be w orking
OK, and t hen wait for ot hers t o find bugs, if t here are any ( as if t here w ere
any doubt ) .
Deadline pressures
Hey, it 's I nt ernet t im e! Tim e t o m ark et det erm ines all. We need ev eryt hing
yest erday, so let 's be j ust like Microsoft and Net scape: release pre- bet a
soft ware as product ion and let our users t est / suffer t hrough our applicat ions.
Managem ent 's lack of underst anding
I T m anagem ent is not orious for not really underst anding t he soft ware
dev elopm ent process. I f we aren't given t he t im e and aut horit y t o w rit e ( writ e,
t hat is, in t he broadest sense, including t est ing, docum ent at ion, refinem ent ,
et c.) our own code properly, w e will always end up wit h buggy j unk t hat no
one w ant s t o adm it ownership of.
Overhead of set t ing up and running t est s
I f it 's a big deal t o writ e and run t est s, t hey w on't get done. I don't hav e t im e,
and t here is always som et hing else t o work on. One consequence of t his point


Term Fly Presents


is t hat m ore and m ore of t he t est ing is handed over t o t he QA depart m ent , if
t here is one. That t ransfer of responsibilit y is, on t he one hand, posit ive.
Professional qualit y assurance professionals can have a t rem endous im pact on
applicat ion qualit y. Yet we dev elopers m ust t ak e and ex ercise responsibilit y
for unit t est ing our own code, ot herwise, t he t est ing/ QA process is m uch m ore
frust rat ing and ext ended.
I wrot e it ; t herefore it work s t he way I int ended it t o work.
The bot t om line is t hat our code alm ost universally needs m ore t est ing. And t he best
way t o do unit t est ing is wit h a form al procedure bui

Dokumen baru


119 3984 16


40 1057 43


40 945 23


21 632 24


28 790 23


60 1348 14


66 1253 50


20 825 17


32 1111 30


41 1350 23