You are on page 1of 20

Some Naming and Coding Standards

April 25, 2000 **DRAFT ** www.plsolutions.com

Please take note: these standards are in DRAFT form; you should read and edit them carefully before applying them in your own organization. PL/Solutions does not warrant their accuracy or applicability to your development process.

Some naming and coding standards for PL/SQL DRAFT Page 1

Table of Contents
Table of Contents..............................................................................................................................................2 Introduction.......................................................................................................................................................3 Benefits of Having Standards.......................................................................................................................3 Format of this Document..............................................................................................................................3 File naming conventions...................................................................................................................................3 Identifier naming conventions..........................................................................................................................4 Scope.............................................................................................................................................................4 Type..............................................................................................................................................................4 Primary Identifier..........................................................................................................................................5 Modifier........................................................................................................................................................5 Suffix............................................................................................................................................................5 Variable Usage Conventions............................................................................................................................6 Cursor Declarations ....................................................................................................................................6 FOR loop index ............................................................................................................................................6 PL/SQL table TYPE ....................................................................................................................................7 Programmer-defined subtype .......................................................................................................................7 PL/SQL Record TYPE ................................................................................................................................7 Code format......................................................................................................................................................8 Indentation....................................................................................................................................................8 Using Case to Aid Readability.....................................................................................................................9 Formatting Single Statements.......................................................................................................................9 Formatting Declarations...............................................................................................................................9 Formatting Multiline Statements................................................................................................................10 Commenting style...........................................................................................................................................10 Comment As you Code...............................................................................................................................10 Explain Why - Not the How.......................................................................................................................10 Make Comments Easy to Enter and Maintain............................................................................................10 Maintain Indentation...................................................................................................................................10 Syntax Guidelines...........................................................................................................................................11 Branching and Labels................................................................................................................................11 Conditional Statements...............................................................................................................................11 REPETITION.............................................................................................................................................13 Avoid Unstructured Exits from Loops.......................................................................................................14 Do not use PL/SQL where you can use a SQL statement instead. ............................................................15 PL/Sql Programming Guidelines....................................................................................................................15 Use Named Constants to Avoid Hard-coding Values................................................................................15 Convert Variables into Named Constants...................................................................................................15 Avoid the recycling of variables.................................................................................................................16 Name Subtypes to Self-document Code.....................................................................................................16 Remove Unused Variables from Programs................................................................................................16 Use %TYPE when a variable represents a column....................................................................................16 Use %TYPE to standardize non-database declarations..............................................................................17 Use Variables to hide complex logic..........................................................................................................18 Building from high-level rules....................................................................................................................18 Converting pseudo-code to PL/SQL...........................................................................................................19 SQL Guidelines..............................................................................................................................................20 Right align the reserved words...................................................................................................................20 Dont skimp on line seperators...................................................................................................................20 Use sensible abbreviations for table and column aliases............................................................................20

Some naming and coding standards for PL/SQL DRAFT Page 2

Introduction
The first and most important thing about standards is to have them. Once you sit down and come up with a set of standards then it becomes very easy to follow them. Remember when you first learned to drive! It seemed to take up all your attention just to keep the car going straight ahead. But now you probably do not even think about it. Standards are the same way. Once you get used to them, they dont even seem to exist. The sign of a good standard is that it facilitates your work. Not come in the way of your work. To arrive at that point takes a lot of hard work. That is where PL/Solutions expertise comes in handy. We at PL/Solutions, led by Steven Feuerstein have spent many years culling different approaches to come up with the following standards. Use them and be happy. First and foremost, standards have to be simple. If there are so many rules that you always need a reference card, then you are never going to use them. On the other hand if they are too simple, you might as well not use one. So you need to strike a balance between too hard and too simple to come up with something that is just right for you. Programming is very personal. It is like writing a story or a piece of music, or painting a picture. So we dont pretend that what we are proposing here is the ultimate truth. This has worked for us. We will be happy if it works for you. Having standards is beneficial to a lot of different people.

Benefits of Having Standards Less decisions to make


Having guidelines to follow means that there are some decisions that you not have to make. You also do not have to justify, argue and defend every decision you make. You may not agree with every part of the standard, but you will be surprised how soon you will be comfortable with the standards.

Easier Maintenance
Maintenance programming becomes easier since the code is easier to read and modify.

Easier to Train
With standard guidelines, it is easy to set up a training program, whether it is a hands on session or a CBT. New hires can be trained in a day or two to conform to the corporate standards.

Easier to Automate
With a well-defined standard you can plug it into an automatic formatter like PL/Formatter from RevealNet and format legacy code to conform to corporate standards.

Format of this Document


This document is organized such that information is easy to find. First a particular standard is defined. Then there is a usage example. Every aspect of programming in PL/SQL is covered. Guidelines are provided for formatting and commenting.

File naming conventions


All PL/SQL program units are stored in the database. Before they are compiled into the database, they are usually created as a text file. Use the following extensions for naming these text files.

Examples:

File Type
Stored Package Body

Extension
pkb

Example
dbmsout.pkb

Some naming and coding standards for PL/SQL DRAFT Page 3

Stored Package Specification Stored Procedure Stored Function Trigger Anonymous block Table creation statement Test script Multiple DDL statements

pks spr sfn trg sql tab tst ddl

dbmsout.pks UpdCust.spr GetCust.sfn cascade.trg testtrg.sql emp.tab dbmssql.tst setup.ddl

Identifier naming conventions


Think of all identifiers as consisting of 5 parts. <Scope><Type><Primary Identifier><Modifier><Suffix>. Of the 5 elements only the primary identifier is required. All others are optional and only make the name better self documenting.

Scope
Scope is the locality of reference. Knowing this is invaluable to the maintenance programmer. Notice that p is added as the scope of a parameter. This is a good way of denoting that a variable is a parameter to the procedure.

Examples:
Locality g l p Description Global Local Parameter Example g_temp l_temp p_param1

Type
Use the simplest possible types there are. There are only two, constants and variables. You can further breakdown these two into the individual data types, but then it gets complicated. We sure do not want to write complicated code.

Examples:
Type c c c v v v Description Constant Constant Constant Variable Variable Variable Example gc_loop_count lc_loop_count pc_loop_count gv_loop_count lv_loop_count pv_loop_count Comment Global constant Local Constant. Parameter Global Variable Local Variable Parameter

In addition to these scalar types, there are other data types that are supported by the PL/SQL language. They are aggregate data types, which are as follows: Type cur vcr tbl rec Description Cursor Cursor(variable) Table Record Example gcur_employee lvcr_employee gtbl_employee ltrec_address

Some naming and coding standards for PL/SQL DRAFT Page 4

One more thing to define. There are two special constructs that are available in PL/SQL. They are Type and Subtype. We are going to treat these as datatypes. Type typ stp Description TYPE SUBTYPE Example gtyp_new_account_table lstp_employee_ID

Primary Identifier
Primary identifier is the most important part of a name. This can be a single word or a phrase. We will talk of lengths of names later but it is always a trade off between length for documentation and brevity for typing purposes. We would want to be optimal. This should pretty much tell the reader the purpose of this identifier. Each corporation should have a list of these prime identifiers in the corporate repository. Some examples are account, student, company, phone etc. We will later on discuss some abbreviating rules. A list of abbreviations is also a part of the corporate repository.

Examples
Account, Student, Company, Phone etc.

Modifier
A modifier further qualifies a primary identifier to make it more readable. These modifiers can either precede or succeed a primary identifier. Some examples are for the prime id address, modifier may be mailing forming the name, MailingAddress. Or for Phone it could be, HomePhone etc. A modifier could also be inserted in the middle of a prime id. For example CustomerName can be modified to read CustomerLastName.

Examples:
Primary Identifier address phone customer_name Modifier mailing home last Position Precede Precede Middle Variable mailing_address home_phone customer_last_name

Suffix
The suffix is used to qualify the identifier further to document the usage of the variable. For example, the suffix is used to denote the type of parameter, as in IN, OUT, or INOUT Type i o io Description Input only parameter Output only parameter Both input and output Example pv_num_items_i pv_sum_o pv_sum_io

Now that some basic standards are defined let us look at how some of these standards are used in practice.

Some naming and coding standards for PL/SQL DRAFT Page 5

Variable Usage Conventions


Now that some basic standards are defined let us look at how some of these standards are used in practice.

Cursor Declarations
Cursors are usually named after the table or a view that is being processed. Use the word cur as the suffix for the variable. You would still specify the scope of the variable as usual. What happens if you pass the cursor in as a parameter? You would end up with two suffixes. Although this is unusual, it works fine. Scope Local Parameter Type cur cur Primary Identifier Account Account Modifier New Old Suffix Null IN Example lcur_new_account pcur_old_account_i

Record based on table or cursor


These records are defined from the structure of a table or cursor. Scope Local Parameter Global Type rec rec rec Primary Identifier Account Account Account Modifier Suffix Null IN Example lrec_account prec_account_i grec_account

If you have more than one record declared for a single cursor, preface the record name with a word that describes it, such as Scope Local Parameter Global Type rec rec rec Primary Identifier Account Account Account Modifier newest duplicate old Suffix Null IN Example lrec_new_account prec_duplicate_account_i grec_old_account

FOR loop index


There are two kinds of FOR loops, numeric and cursor, each with a corresponding numeric or record loop index. In a numeric loop you should incorporate the word "index" or "counter" or some similar suffix into the name of the loop index, such as: Scope Local Type v Primary Identifier year Modifier Suffix idx Example lv_year_idx

In a cursor loop, the name of the record, which serves, as a loop index should follow the convention described above for records.

Some naming and coding standards for PL/SQL DRAFT Page 6

PL/SQL table TYPE


In PL/SQL Version 2 you can create PL/SQL tables, which are similar to one-dimensional arrays. In order to create a PL/SQL table, you must first execute a TYPE declaration to create a table datatype with the right structure. Scope Local Global Type typ typ Primary Identifier Account Account Modifier new old Suffix table table Example ltyp_new_account_table gtyp_old_account_table

PL/SQL table
A PL/SQL table is declared based on a table TYPE statement, as indicated above. In most situations, use the same name as the table type for the table, but leave off the type part of the suffix. The following examples correspond to the previous table types: Scope Local Global Type tbl tbl Primary Identifier Account Account Modifier new old Suffix Example ltbl_new_account gtbl_old_account

Programmer-defined subtype
In PL/SQL Version 2.1 you can define subtypes from base datatypes. Scope Local Global Type stp stp Primary Identifier Primary_key Large_string Modifier Suffix Example lstp_primary_key gstp_large_string

PL/SQL Record TYPE


In PL/SQL Version 2 and above, you can create records with a structure you specify (rather than from a table or cursor). To do this, you must declare a type of record, which determines the structure number, and types of columns). Use a rectype prefix in the name of the TYPE declaration as follows: Scope Local Global Type typ typ Primary Identifier Account Account Modifier new old Suffix record record Example ltyp_new_account_record gtyp_old_account_record

Some naming and coding standards for PL/SQL DRAFT Page 7

Programmer-defined record instance


Once you have defined a record type, you can declare actual records with that structure. Now you can drop the type part of the rectype prefix; the naming convention for these programmer-defined records is the same as that for records based on tables and cursors: Scope Local Global Type rec rec Primary Identifier Account Account Modifier new old Suffix Example ltyp_new_account_record gtyp_old_account_record

Code format
How you format your code in your source code is an intensely personal issue. Most people use conventions that are imposed by corporate standards. But when there is no standard available then most programmers feel lost. They end up using a mish-mash of techniques that makes the resulting code hard to read. So it is important that every programmer develop a consistent and cohesive coding style that is easy to read and maintain. There are two points of view to formatting. One is the developers view. The other is the maintainers view. A good standard should meet the needs of both views. There is really one fundamental reason for formatting your code: Reveal and reinforce the logical structure of your program. Writing code to please the eye is a waste of time. Code never stays that way for long. What is more important is to show the structure and the intent of the program. We truly believe that the machine should do this for the programmer. So if you follow the rules set forth here, there will be a tool in the future that will magically transform your program into a listing that could be framed as a work of art.

Indentation
Indentation is one of the most common and effective ways to display a programs logical structure. Programs that are indented are lot easier to read than those that are not. Please be aware that indentation is a double edged sword. It is very easy to mislead with inconsistent indentation.

General indentation rules


Indent and align nested control structures, continuation lines, and embedded units consistently. Distinguish between indentation for nested control structures and for continuation lines. Use spaces for indentation, not the tab character (Nissen and Wallis, 1984)

Indentation Recommendations
The following indentation conventions are recommended. Note that the minimum indentation is described. More spaces may be required for the vertical alignment recommended in subsequent guidelines. Use three spaces as the basic unit of indentation for nesting. Use three spaces as the basic unit of indentation for continuation lines.

In our experience 3 or 4 spaces is the ideal way to indent. This amount of spacing not only adequately reveals the logical structure of the code but also keeps the statements close enough together to read comfortably. You also dont run off the edge of the page with deeply nested structures. Although you should try avoiding deeply nested structures, since most human brains cant stack more that 5 items at a time.

Some naming and coding standards for PL/SQL DRAFT Page 8

Alignment
As mentioned above trying to keep programs pretty is a lot of work. Hence the following recommendations. Do not try to align statements, operators etc. vertically. This not only takes up time, but also leads to realigning text continuously. Indent continuation lines the same three spaces. Provide one declaration per line (at most). Place the first parameter specification on a separate line from the function or procedure declaration. If any of the parameter types are forced beyond the line length limit, place the first parameter specification on a new line indented as for continuation lines. Place one formal parameter specification per line. You may choose to place more than one parameter per line, but always follow the previous rule.

Using Case to Aid Readability


PL/SQL code is made up of many different components: variables, form items, report fields, procedures, functions, loops, etc. All these fall into two major categories. Reserved words and program specific identifiers. Reserved words are those language elements that are used by PL/SQL. They have special meaning to the compiler and hence are reserved. Program specific identifiers are the names that a programmer gives to the various components of program such as variables, constants, procedures etc. The PL/SQL compiler treats these two types of text very differently. You can improve the readability of the code greatly by reflecting this difference in the way the text is displayed. Using indentation highlights the logical structure of a program. To distinguish between reserved words and program specific identifiers, use of the upper and lowercase strategy is recommended. Use all UPPER case of reserved words and lower case of program specific identifiers. This increases the readability of the code.

Formatting Single Statements


Most of the programs consist of single statements. Consistent approach to formatting and grouping such statements will improve the readability of the program. The following are recommended rules. Use at most one statement per line PL/SQL uses a logical line terminator, semicolon(;). This allows for placing more than one statement per line as well as continuing a single statement on multiple lines.

Use white space inside a statement. Always include a space between an identifier and a separator.

Use spaces to make module calls and their parameter lists more undestandable.

Formatting Declarations
Declaration section is used to declare local variables and other structures uses in the PL/SQL block. The following rules are recommended. Place one declaration on each line This follows the same logic that was described previously. Ignore alignment for declarations

Some naming and coding standards for PL/SQL DRAFT Page 9

This again is a personal preference. But keeping declarations aligned is probably more trouble than it is worth. If the program is developed and maintained by a single programmer, may be this has some value. In our experience this declarations do not stay aligned for very long.

Formatting Multiline Statements


As mentioned previously, PL/SQLs logical line structure allows for very long strings of text for statements, which may not fit on a traditional line of 80 - 132 columns. So it is easy to spread statements like this across many lines, which makes it difficult to read. Here are some recommendations. Use indentation to offset all continuation lines under the first line. This is the most important guideline. By indenting the continuation lines the same 3 spaces that are recommended, they are subsumed under the first line. Place the module name on a separate line from the parameters, Indent module-call continuation lines to align parameters vertically.

Make it obvious that a statement is continued.

Commenting style
There are two types of comments. Internal and external. Here we talk about internal comments, which are comments that are part of the program. You can avoid a lot of comments if you write self documenting code. If you apply the guidelines specified in this document, you would avoid writing a lot of comments.

Comment As you Code


Documenting after the fact is a losing proposition. So plan on commenting as you go. Commenting as you approach leads to better continuity as you code, as well as programs with fewer bugs. By commenting, you are trying to convey to someone else what the program is doing. This always clarifies things in your mind.

Explain Why - Not the How


Avoid documenting the obvious. Most programmers are good at reading code. If your comments only repeat that is going on in the code, then they are just wasting space. What is useful is to explain why you are doing something, with a function, procedure or a section of a procedure.

Make Comments Easy to Enter and Maintain


Avoid the tendency to make things look pretty. It takes too long to create as well as to maintain. When you change a comment you should not have to reformat all the lines in the comment. As far as documenting goes, fancy equates to high maintenance.

Maintain Indentation
Comments should reinforce indentation and therefore the logical structure of the program. Always starting your comments in the first column disrupts the logical flow of code. Always indent the comments at the same level as the code which they describe.

Some naming and coding standards for PL/SQL DRAFT Page 10

Syntax Guidelines
Branching and Labels
If you have programmed in Assembler or in an older version of FORTRAN, you are aware that the only form of flow control was using either a Jm Goto or . In early FORTRAN every line was required to be up numbered. These numbers were used as labels for branching. Early BASIC also used this numbering scheme. Procedural languages introduced labels that replaced line numbers. There is no need to number each line anymore. PL/SQLs G label causes execution to continue from statement where the label is o located. Labels are variables with a << prefix and a >> suffix. For example <<start>> is a label.

Do not use gotos


We strongly recommend not using Goto programs. Goto for unreadable, and high s in the s make maintenance code. There is only one instance where a Goto be used in PL/SQL. That is for exiting a should procedure. In addition to this If you must use Goto make them forward only. Typical use for a forward s, then only Gotojump to an exit point so that any clean up code can be executed before exiting. is to

Conditional Statements If...Then...Else


Conditional statements either skip or execute statements based on a conditional expression which must evaluate to True or False. There are three variations of syntax for this statement.

Keywords on Separate Lines


Place the keywords(IF, THEN, ELSE, ELSIF, ENDIF) on separate lines. We prefer this format for two reasons. Firstly, it places all the keywords in the same column making it easier to eyeball the logical structure. Secondly it creates white space around the keywords. Indent statements from the keywords by the customary 3 spaces.

Avoid Unnecessary Nested IFs


The following statements are equivalent. The flat structure expresses the logic more clearly and with less code.

Nested
IF <condition1> THEN ... ELSE IF <Condition2> THEN ELSE IF <Condition3> THEN ELSE IF <Condition4> THEN IF <condition1> THEN ELSIF <Condition2> THEN ELSIF <Condition3> THEN ELSIF <Condition4> THEN END IF;

Flat

Some naming and coding standards for PL/SQL DRAFT Page 11

END IF; END IF; END IF; END IF;

Use Nested IFs to Defer Expensive Executions


Generally, you will want to use an ELSIF statement instead of nested IFs. A good candidate for a nested IF, however, arises when one condition is much more resourceintensive than the other. Suppose condition A consumes .05 CPU seconds and condition B consumes 10 minutes. You dont want to execute B unless A is TRUE -- and you dont want to rely on the compiler to decide which clause is evaluated first.

Ensure Conditions in ELSIF Clauses are Exclusive


The implication of ELSIF clauses is that if one condition is fulfilled, all others would fail -- they are mutually exclusive. The following IF statement is a classic misuse of ELSIF clauses. It might not cause any errors, but that would just be a matter of luck. In many cases, the issue of exclusivity is less obviously determined.

Use Boolean Elements to Improve Readability


You can code real Boolean variables and literals (TRUE, FALSE and NULL values) in PL/SQL. Boolean variables and functions allow you to greatly improve readability of programs. You can hide complex expressions behind a name, which describes the expression. Compare the two IF statements below.

Avoid IF With Boolean Variables


Sometimes you will code or come across conditional statements which, while valid, are unneccesary and cumbersome. Replace this IF statement:

Some naming and coding standards for PL/SQL DRAFT Page 12

Remember:

You can assign a Boolean expression directly to a Boolean variable.

REPETITION
Programming involves performing a task repeatedly, until a particular condition is met. Looping constructs of a language support this need. There are three basic types of looping. 0 or more loops, 1 or more loops, and Loop for a specified number of times. PL/SQL supports all three types.

0 or More times Loop


These are loops where the testing is done at the beginning of a loop. If the condition evaluates to true then the statements with in the loop are executed. Otherwise the statements are skipped and execution is transferred to the statements following the loop.

WHILE LOOP ... END LOOP


The syntax for a W as follows: is H WIE cL H o Statements Again keep all the keywords in the same column, while indenting the keyword columns by 3 spaces.

1 or more times loop


These are loops where testing is done as part of the executable portion of the loop, or at the bottom of the loop. PL/SQL only provides a basic type of a loop, which is an infinite loop. The statements with in the loop are executed an infinite number of times.

LOOP... END LOOP Loop for specified number of times


PL/SQL provides for two types of looping constructs. They are the NUMERIC FOR loop and the CURSOR FOR loop

Numeric For Loop

Cursor For Loop

Again notice that the indentation is consistent at 3 spaces.

Some naming and coding standards for PL/SQL DRAFT Page 13

Never Declare the FOR Loop Index

Do not declare the loop index variable (year_ind in the example above). PL/SQL does that for you automatically. For both numeric and cursor FOR loops, the identifier after the FOR keyword is automatically declared by PL/SQL with type BINARY_INTEGER or a record to match the cursor. If you declare a variable with same name as loop index, it is a different variable. You could refer to the FOR loop index outside the loop and your code will compile, but it will not be doing what you think or what you want. This code will compile, but it will not work as intended. This kind of code is very hard to understand and debug.

Suppose you need the value of the loop index (year_count in the following example) for debugging:

In this case use a local variable and copy the loop index to local variable:

Avoid Unstructured Exits from Loops


Do not EXIT or RETURN out of a FOR loop.

Some naming and coding standards for PL/SQL DRAFT Page 14

A FOR loop should only be used when you want to execute the body a fixed number of times. Stay for the duration or use a different loop construct. Do not use the EXIT syntax in a WHILE loop. The loop should be terminated only when the condition in the boundary evaluates to FALSE. Note: if an exception is raised and the loop stops, that is a legitimate early termination.

Do not use PL/SQL where you can use a SQL statement instead.
The SQL statement will often be much faster. You should replace PL/SQL loops with single SQL statements when possible. Slower PL/SQL Version

Faster, Simpler SQL Version

PL/Sql Programming Guidelines


Now that naming standards are defined we offer you some general guidelines for good programming practices. Most them are universal and would apply to any type of a programming effort. But we are only speaking in terms of PL/SQL here.

Use Named Constants to Avoid Hard-coding Values


Follow these simple guidelines regarding literals in all of your applications: 1. Remove all literals (within reason) from your code. Instead, declare constants, which hold those literal values. 2. Allow the value of that literal (now a constant) to be set in only one place in your code, preferably with call to a procedure. This procedure can be run on start-up of the application, or from the initialization section of a package. 3. Provide a single way to retrieve the literal value, preferably through a call to a function. Don't let any program reference the literal directly. This way you reserve the right and ability to change at any time the data structures you use to store that literal -- without affecting any of the programs which rely on that constant.

Convert Variables into Named Constants


If you find that you have written a program in which a variable's value does not change, you should first determine if that behavior is correct. If all is as it should be, you should then convert that variable to a constant. Why should you bother converting "read only" variables to constants (and named ones at that)? Because when you "tell it and use it like it is," the program explains itself more clearly. The declaration of a named identifier as a constant gives you information about how it should be used in the program.

Some naming and coding standards for PL/SQL DRAFT Page 15

If you do convert a variable to a constant, you should also change its name. This will help to remind anyone reading the code that your identifier refers to a constant and cannot be changed.

Avoid the recycling of variables


Each variable and constant you declare should have one purpose and one purpose only. The name for that variable or constant should describe, as clearly as possible, that single-minded purpose. The only reason to create generically named variables and constants is to save you, the developer, typing time. That is always a terrible reason for a coding style or change in a programming effort. Reliance on a "time-saver" short cut should raise a red flag: you are probably doing (or avoiding) something now for which you will pay later.

Name Subtypes to Self-document Code


One of the most compelling reasons for creating your own subtypes is to provide application- or function-specific datatypes that self-document your code. A programmer-defined subtype hides the generic "computer datatype" and replaces it with a datatype that has meaning in your own environment. In naming your subtype, you should consequently avoid references to the underlying datatype and concentrate instead on the business use of the subtype. Suppose you are building a hotel reservation system. A very useful subtype would be a room number; it is a special kind of NUMBER and is used throughout the application. So define a subtype called room_number_type, which you can then use whenever you need to defined a variable of type room number.

Remove Unused Variables from Programs


You should go through your programs and remove any part of your code that is no longer used. This is a relatively straightforward process for variables and named constants. Simply execute searches for a variable's name in that variable's scope. If you find that the only place it appears is its declaration, delete the declaration and, by doing so, delete one more potential question mark from your code. There is never be a better time to review all the steps you took and understand the reasons you took them than immediately upon completion of your program. If you wait, you will find it particularly difficult to remember those parts of the program which were needed at one point, but were rendered unnecessary in the end. "Dead zones" in your code become sources of deep insecurity for maintenance programmers.

Use %TYPE when a variable represents a column


Always use the %TYPE attribute to declare variables which are actually PL/SQL representations of database values. This includes a lot of your variables. Using %TYPE sometimes takes lots more typing, but it improves your code substantially.

Some naming and coding standards for PL/SQL DRAFT Page 16

Suppose you have a procedure in Oracle Forms that formats information about a customer. You need to declare a variable for each attribute of the customer: first name, last name, address, Social Security Number, etc. Declare them using %TYPE as follows:

Using the %TYPE attribute ensures that your variables stay synchronized with your database structure. Just as importantly, though, this declaration section is more self documenting now. The %TYPE attribute provides important information to anyone reviewing the code, stating: "These variables represent my columns in the program. When you see one of these variables, think 'database column'." This correlation makes it easier to understand the code, easier to change the code, and easier to recognize when one of those variables is used in an inappropriate manner.

Use %TYPE to standardize non-database declarations


While many (perhaps even most) of your local PL/SQL variables are directly related to database columns, at least some of your variables are local-only, perhaps calculated values based on database columns. Use the %TYPE attribute to infer a variable's datatype from another, previously defined PL/SQL variable. The following declarations use this alternative source:

The variable called revenue_data acts as the standard variable for revenue data. Whenever we declare the total_revenue variable (or any other revenue-related variables), we can base it on the general revenue_data variable. By doing this, we guarantee a consistent declaration of revenue variables. Furthermore, if the revenue datatypes ever need to be changed again, we only have to change the way that revenue_data is declared and recompile. All variables declared with revenue_data%TYPE will automatically adjust. Note that while max_available_date has a default value as well, it is not applied to last_ship_date. Everything up to the optional default value assignment (initiated with a DEFAULT keyword or assignment operator) in a declaration is used in the %TYPE declaration, such as NOT NULL and the datatype. The default value, if specified in the source variable declaration, is ignored. To make it easiest for individual developers to be aware of and make use of standard variable declarations, consider creating a package that contains only standard variable declarations and any code necessary to initialize them, as follows:

Some naming and coding standards for PL/SQL DRAFT Page 17

Use Variables to hide complex logic


A variable is a chunk of memory that has a name. A variable can hold a simple value. It can also be assigned the value of the outcome of an arbitrarily complicated expressioneither through a default value setting or an assignment. In this way a variable can "represent" that complex expression and thus be used in place of that expression in your code. The result is a program which is easy to read and maintain. Consider the following code fragment:

If you skip past the complicated Boolean expressions and look at the code executed in each IF and ELSIF clause you can "reverse-engineer" the understanding of the code. It looks like the IF statement is used to determine the method by which an order should be shipped. Unfortunately, it would be very difficult to discern this fact from the conditions in the IF statement. Those Boolean expressions with multiple components are, in and of themselves, almost impossible to interpret without drawing a diagram. If there is an error in this logic, no one but the original author would be able to readily untangle the knot.

Building from high-level rules


You should, in general, avoid implementing complicated expressions and logic until you have mapped out and verified that logic independent of PL/SQL code. Are you working from specifications? Then for the above code, your specifications might say something like this: RULE 1: "If the order is overdue and the customer priority is high, ship the products ordered using express delivery." RULE 2: "If the order is not overdue or the order is overdue but the customer priority is normal, then use standard ground delivery." Before you dive into the PL/SQL IF statement, write some pseudo-code based on your specifications. Here is an example:

The next step would be to rewrite this nested IF statement as follows:

Even before writing a line of code, we have been able to simplify the logic which meets this specification. At this point we dont know what it means for an order to be overdue. We don't know how to

Some naming and coding standards for PL/SQL DRAFT Page 18

tell if a customer's priority is high. We don't really need to know these details yet. The focus is to make sure we understand the logical requirements. Once this is done, we can recast the pseudo-code as real PL/SQL.

Converting pseudo-code to PL/SQL


My first pass in a conversion to PL/SQL would be a more-or-less direct translation:

We don't know how ship_order will behave and, again, at this moment we dont care. We'll employ top-down design to "fill in the blanks" and then work out the details later. The conditional expression:

substitutes named variables for the pseudo-code. To figure out exactly how these variables should be assigned their values, We need to look back at my requirements. Here is what I find: DEFINITION 1: "An order is overdue if the shipping date is within the next three months or the order status is open and the order was placed more than two months ago." DEFINITION 2: "A customer has a high priority if its priority type is equal to HIGH." This last sentence is less a requirement than an implementation instruction. Be that as it may, instead of creating a function for each of these conditions, we can declare Boolean named constants and assign a value to those constants based on the variables representing the order and customer, as shown below:

In this final version of the IF statement, weve used the order_overdue constant to abstract out or hide the two-part check against the order and ship dates. Now the IF-THEN code is much easier to read; in fact, it all but explains itself through the names of the constants. This self-documenting capability reduces the need for separate comments in the code. By consolidating the redundant code, it also makes it easier to maintain the application. If the conditions which make an order "overdue" change, we do not need to hunt through the code for all the places which perform the order_overdue test. We need only change the default value given to the order_overdue constant. This approach can be taken a step further by placing the business rule logic into a Boolean function. We can then call this function from any of our programs and avoid reproducing the logic in that declaration statement.

Some naming and coding standards for PL/SQL DRAFT Page 19

SQL Guidelines
Right align the reserved words Select

Insert

Update

Delete Dont skimp on line seperators


Within clauses Use separate line for each expression in a SELECT list Place each table in a FROM clause on its own line Place each expression in WHERE clause on its own line

Use sensible abbreviations for table and column aliases


Instead of a code segment such as,

Use a code segment such as,

Some naming and coding standards for PL/SQL DRAFT Page 20

You might also like