Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier...

35
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

Transcript of Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier...

Page 1: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

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

Page 2: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

Table of ContentsTable of Contents.............................................................................................................................................2Introduction......................................................................................................................................................3

Benefits of Having Standards.......................................................................................................................3Format of this Document..............................................................................................................................3

File naming conventions...................................................................................................................................3Identifier naming conventions..........................................................................................................................4

Scope............................................................................................................................................................4Type..............................................................................................................................................................4Primary Identifier.........................................................................................................................................5Modifier........................................................................................................................................................5Suffix............................................................................................................................................................5

Variable Usage Conventions............................................................................................................................5Cursor Declarations......................................................................................................................................6FOR loop index............................................................................................................................................6PL/SQL table TYPE.....................................................................................................................................7Programmer-defined subtype.......................................................................................................................7PL/SQL Record TYPE.................................................................................................................................7

Code format......................................................................................................................................................8Indentation....................................................................................................................................................8Using Case to Aid Readability.....................................................................................................................9Formatting Single Statements.......................................................................................................................9Formatting Declarations.............................................................................................................................10Formatting Multiline Statements................................................................................................................10

Commenting style...........................................................................................................................................11Comment As you Code..............................................................................................................................11Explain Why - Not the How.......................................................................................................................11Make Comments Easy to Enter and Maintain............................................................................................11Maintain Indentation..................................................................................................................................11

Syntax Guidelines...........................................................................................................................................11Branching and Labels.................................................................................................................................11Conditional Statements...............................................................................................................................12REPETITION.............................................................................................................................................14Avoid Unstructured Exits from Loops.......................................................................................................18Do not use PL/SQL where you can use a SQL statement instead..............................................................18

PL/Sql Programming Guidelines....................................................................................................................18Use Named Constants to Avoid Hard-coding Values................................................................................18Convert Variables into Named Constants..................................................................................................19Avoid the recycling of variables.................................................................................................................19Name Subtypes to Self-document Code.....................................................................................................19Remove Unused Variables from Programs................................................................................................20Use %TYPE when a variable represents a column....................................................................................20Use %TYPE to standardize non-database declarations..............................................................................20Use Variables to hide complex logic..........................................................................................................21Building from high-level rules...................................................................................................................22Converting pseudo-code to PL/SQL..........................................................................................................23

SQL Guidelines..............................................................................................................................................25Right align the reserved words...................................................................................................................25Don’t skimp on line seperators...................................................................................................................25Use sensible abbreviations for table and column aliases............................................................................26

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

Page 3: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

IntroductionThe 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 don’t 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 don’t 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 makeHaving 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 MaintenanceMaintenance programming becomes easier since the code is easier to read and modify.

Easier to TrainWith 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 AutomateWith 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 DocumentThis 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 conventionsAll 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 Extension Example

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

Page 4: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

Stored Package Body pkb dbmsout.pkbStored Package Specification pks dbmsout.pksStored Procedure spr UpdCust.sprStored Function sfn GetCust.sfnTrigger trg cascade.trgAnonymous block sql testtrg.sqlTable creation statement tab emp.tabTest script tst dbmssql.tstMultiple DDL statements ddl setup.ddl

Identifier naming conventionsThink 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.

ScopeScope 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 Description Exampleg Global g_templ Local l_tempp Parameter p_param1

TypeUse 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 Description Example Commentc Constant gc_loop_count Global constantc Constant lc_loop_count Local Constant.c Constant pc_loop_count Parameterv Variable gv_loop_count Global Variablev Variable lv_loop_count Local Variablev Variable pv_loop_count 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 Description Examplecur Cursor gcur_employeevcr Cursor(variable) lvcr_employee

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

Page 5: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

tbl Table gtbl_employeerec Record ltrec_address

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 Description Exampletyp TYPE gtyp_new_account_tablestp SUBTYPE lstp_employee_ID

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

ExamplesAccount, Student, Company, Phone etc.

ModifierA 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 Modifier Position Variableaddress mailing Precede mailing_addressphone home Precede home_phonecustomer_name last Middle customer_last_name

SuffixThe 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 Description Examplei Input only parameter pv_num_items_io Output only parameter pv_sum_oio Both input and output 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

Page 6: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

Variable Usage ConventionsNow 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 Type Primary Identifier Modifier Suffix ExampleLocal cur Account New Null lcur_new_accountParameter cur Account Old IN pcur_old_account_i

Record based on table or cursor

These records are defined from the structure of a table or cursor.

Scope Type Primary Identifier Modifier Suffix ExampleLocal rec Account Null lrec_accountParameter rec Account IN prec_account_iGlobal rec Account 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 Type Primary Identifier Modifier Suffix ExampleLocal rec Account newest Null lrec_new_accountParameter rec Account duplicate IN prec_duplicate_account_iGlobal rec Account old 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 Type Primary Identifier Modifier Suffix ExampleLocal v year idx lv_year_idx

FOR lv_year_idx IN 1 .. 12

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

Page 7: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

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

FOR lrec_emp IN lcur_emp

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 Type Primary Identifier Modifier Suffix ExampleLocal typ Account new table ltyp_new_account_tableGlobal typ Account old table gtyp_old_account_table

TYPE ltyp_new_account_table IS TABLE OF ...;

TYPE gtyp_old_account_table IS TABLE OF ...;

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 Type Primary Identifier Modifier Suffix ExampleLocal tbl Account new ltbl_new_accountGlobal tbl Account old gtbl_old_account

ltbl_new_account ltyp_new_account_table;

gtbl_old_account gtyp_old_account_table;

Programmer-defined subtype

In PL/SQL Version 2.1 you can define subtypes from base datatypes.

Scope Type Primary Identifier Modifier Suffix ExampleLocal stp Primary_key lstp_primary_keyGlobal stp Large_string gstp_large_string

SUBTYPE lstp_primary_key IS BINARY_INTEGER;

SUBTYPE gstp_large_string IS VARCHAR2;

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

Page 8: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

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 Type Primary Identifier Modifier Suffix ExampleLocal typ Account new record ltyp_new_account_recordGlobal typ Account old record gtyp_old_account_record

TYPE ltyp_new_account_record IS RECORD ... ;

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 Type Primary Identifier Modifier Suffix ExampleLocal rec Account new ltyp_new_account_recordGlobal rec Account old gtyp_old_account_record

Code formatHow 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 developer’s view. The other is the maintainer’s 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.

IndentationIndentation is one of the most common and effective ways to display a program’s 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)

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

Page 9: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

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 don’t run off the edge of the page with deeply nested structures. Although you should try avoiding deeply nested structures, since most human brains can’t stack more that 5 items at a time.

AlignmentAs 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 ReadabilityPL/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 StatementsMost 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 linePL/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.

lv_var1 := 0 ; lv_var2 := 1 ; -- This is valid

lv_var1 := 0 ; -- But code this

lv_var2 := 1 ; -- way instead.

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

Page 10: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

Use white space inside a statement.

Always include a space between an identifier and a separator.

lv_var1:=0; -- This is valid

lv_var1 := 0 ; -- But code this way for clarity.

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

calc_totals(pv_company_id, pv_end_of_year_date,pv_total_type); -- Valid

calc_totals (pv_company_id, pv_end_of_year_date, pv_total_type; -- Clearer

Formatting DeclarationsDeclaration 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

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

Gen_stats

(pv_company_id,

pv_last_year_date,

pv_rollup_type,

pv_total) ; Make it obvious that a statement is continued.

FOR month_index IN -- the IN statement needs its

Lv_first_month .. lv_last_month -- range

LOOP

gv_q1_sales :=

lv_month1_sales + -- An assignment cannot end with a “+”.

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

Page 11: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

lv_month2_sales +

lv_month3_sales;

Gen_stats

(pv_company_id, pv_last_year_date, -- Last comma indicates

pv_rollup_type, pv_total) ; -- other parameters to follow.

Commenting styleThere 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 CodeDocumenting 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 HowAvoid 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 MaintainAvoid 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 IndentationComments 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.

Syntax Guidelines

Branching and LabelsIf 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 Jump or Goto. In early FORTRAN every line was required to be 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/SQL’s Goto label causes execution to continue from statement where the label is located. Labels are variables with a ‘<<’ prefix and a ‘>>’ suffix. For example <<start>> is a label.

Do not use gotosWe strongly recommend not using Gotos in the programs. Gotos make for unreadable, and high

maintenance code. There is only one instance where a Goto should be used in PL/SQL. That is for exiting

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

Page 12: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

a procedure. In addition to this If you must use Gotos, then make them forward only. Typical use for a forward only Goto is to jump to an exit point so that any clean up code can be executed before exiting.

Conditional Statements

If...Then...ElseConditional 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 LinesPlace 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 FlatIF <condition1> IF <condition1>THEN THEN ... …ELSE ELSIF <Condition2> IF <Condition2> THEN THEN … … ELSIF <Condition3> ELSE THEN IF <Condition3> … THEN ELSIF <Condition4> … THEN ELSE … IF <Condition4> END IF; THEN … END IF; END IF; END IF;END IF;

Use Nested IFs to Defer Expensive ExecutionsGenerally, 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 resource-intensive than the other. Suppose condition A consumes .05 CPU seconds and condition B consumes 10 minutes. You don’t want to execute B unless A is TRUE -- and you don’t want to rely on the compiler to decide which clause is evaluated first.

IF condition A

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

Page 13: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

THEN

IF condition B

THEN

...

END IF;

END IF;

Ensure Conditions in ELSIF Clauses are ExclusiveThe 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.

IF sal BETWEEN 0 AND 10000

THEN

...

ELSIF sal BETWEEN 10000 AND 20000

THEN

...

ELSIF sal BETWEEN 20000 AND 30000

THEN

...

END IF;

Use Boolean Elements to Improve ReadabilityYou 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.

IF total_sal BETWEEN 10000 AND 50000 AND

emp_status (emp_rec.empno) = 'N' AND

(MONTHS_BETWEEN

(emp_rec.hiredate, SYSDATE) > 10)

THEN

give_raise (emp_rec.empno);

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

Page 14: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

END IF;

IF eligible_for_raise (emp_rec.empno)

THEN

give_raise (emp_rec.empno);

END IF;

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:

IF hiredate < SYSDATE

THEN

date_in_past := TRUE;

ELSE

date_in_past := FALSE;

END IF;

With this:

date_in_past :=

hiredate < SYSDATE;

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

REPETITIONProgramming 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 LoopThese 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 WHILE...LOOP is as follows:

WHILE conditionLOOP Statements

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

Page 15: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

END LOOP

Again keep all the keywords in the same column, while indenting the keyword columns by 3 spaces.

1 or more times loopThese 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 statements;END LOOP;

This loop can be turned into a 1 or more times loop by using the EXIT WHEN clause.

LOOP Statements; EXIT WHEN Condition;END LOOP;

Loop for specified number of timesPL/SQL provides for two types of looping constructs. They are the NUMERIC FOR loop and the

CURSOR FOR loop

Numeric For Loop

FOR lv_for_index IN low_value .. high_valueLOOP statements

END LOOP;

Cursor For Loop

FOR lv_record_index IN my_cursorLOOP statements

END LOOP;

Again notice that the indentation is consistent at 3 spaces.

Never Declare the FOR Loop Index

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

Page 16: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

FOR year_ind IN 1 .. 20

LOOP

calc_profits (year_ind);

END LOOP;

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.

DECLARE

CURSOR emp_cur IS

SELECT empno, ename FROM emp;

emp_rec emp_cur%ROWTYPE;

BEGIN

FOR emp_rec IN emp_cur

LOOP

display_emp (emp_rec.ename);

END LOOP;

IF emp_rec.ename = 'FEUERSTEIN'

THEN

give_raise

(emp_rec.empno, 1000000);

END IF;

END;

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

DECLARE year_count INTEGER := NULL;

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

Page 17: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

BEGIN

FOR year_count IN 1 .. 20

LOOP

calc_pnl (year_count);

END LOOP;

EXCEPTION

WHEN NO_DATA_FOUND

THEN

DBMS_OUTPUT.PUT_LINE

('Error in year ' ||

TO_CHAR (year_count));

END;

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

DECLARE my_count INTEGER := NULL;

BEGIN

FOR year_count IN 1 .. 20

LOOP

my_count := year_count;

calc_pnl (year_count);

END LOOP;

EXCEPTION

WHEN NO_DATA_FOUND

THEN

DBMS_OUTPUT.PUT_LINE

('Error in year ' ||

TO_CHAR(my_count));

END;

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 17

Page 18: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

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

FOR year_count IN 1 .. 20

LOOP

INSERT INTO v1table1

SELECT * FROM v1table2

WHERE yr_nu = year_count;

END LOOP;

Faster, Simpler SQL Version

INSERT INTO v1table1

SELECT * FROM v1table2

WHERE yr_nu BETWEEN 1 AND 20;

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.

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

Page 19: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

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.

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

SUBTYPE room_number_type IS POSITIVE;

...

-- A declaration using the subtype:

open_room room_number_type;

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.

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

Page 20: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

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.

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:

PROCEDURE format_customer

IS

first_name customer.cust_fname%TYPE;

last_name customer.cust_lname%TYPE;

address customer.cust_addr_l1%TYPE;

city customer.cust_city%TYPE;

state customer.cust_state_abbrev_cd%TYPE;

soc_sec# customer.cust_soc_sec_number%TYPE;

BEGIN

... interact with database customer information ...

END;

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 declarationsWhile 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:

DECLARE

revenue_data NUMBER(20,2);

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

Page 21: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

total_revenue revenue_data%TYPE;

--

max_available_date DATE := LAST_DAY (ADD_MONTHS (SYSDATE, 3));

last_ship_date max_available_date%TYPE;

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:

PACKAGE std_vartypes

IS

/* Source for all revenue-related declarations */

revenue_data NUMBER(20,2);

/* Source for any Y/N flags—when you don't use Booleans */

flag_data CHAR(1);

/* Standard format for primary key columns */

primary_key_data NUMBER (10);

END std_vartypes;

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 expression—either 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 (shipdate < ADD_MONTHS (SYSDATE, +3) OR

order_date >= ADD_MONTHS (SYSDATE, -2)) AND

Some naming and coding standards for PL/SQL – DRAFT – Page 21

Page 22: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

cust_priority_type = 'HIGH' AND

order_status = 'O'

THEN

ship_order ('EXPRESS');

ELSIF (order_date >= ADD_MONTHS (SYSDATE, -2) OR

ADD_MONTHS (SYSDATE, 3) > shipdate) AND

order_status = 'O'

THEN

ship_order ('GROUND');

END IF;

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:

IF order-overdue

THEN

IF customer-priority-is-high

THEN

ship-express;

ELSE

ship-ground;

END IF;

Some naming and coding standards for PL/SQL – DRAFT – Page 22

Page 23: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

ELSE

ship-ground;

END IF;

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

IF order-overdue AND IF customer-priority-is-high

THEN

ship-express;

ELSE

ship-ground;

END IF;

Even before writing a line of code, we have been able to simplify the logic which meets this specification. At this point we don’t know what it means for an order to be overdue. We don't know how to 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:

BEGIN

IF order_overdue AND high_priority

THEN

ship_order ('EXPRESS');

ELSE

ship_order ('GROUND');

END IF;

END;

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

The conditional expression:

order_overdue AND high_priority

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

Some naming and coding standards for PL/SQL – DRAFT – Page 23

Page 24: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

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:

DECLARE

/* I hide my business rule behind this variable. */

order_overdue CONSTANT BOOLEAN

DEFAULT (shipdate < ADD_MONTHS (SYSDATE, +3) OR

order_date >= ADD_MONTHS (SYSDATE, -2)) AND

order_status = 'O';

high_priority CONSTANT BOOLEAN

DEFAULT cust_priority_type = 'HIGH';

BEGIN

IF order_overdue AND high_priority

THEN

ship_order ('EXPRESS');

ELSE

ship_order ('GROUND');

END IF;

END;

In this final version of the IF statement, we’ve 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 24

Page 25: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

SQL Guidelines

Right align the reserved words

Select

SELECT last_name, first_name

FROM employee

WHERE department_id = 15

AND hire_date < SYSDATE;

Insert

INSERT INTO employee

(employee_id, … )

VALUES

(105, …);

Update

UPDATE employee

SET hire_date = SYSDATE

WHERE hire_date IS NULL

AND termination_date IS NULL

Delete

DELETE FROM employee

WHERE department_id = 15;

Don’t skimp on line seperatorsWithin 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

SELECT last_name,

C.name

MAX (SH.salary) best_salary_ever

FROM employee E

Company C

Salary_history SH

WHERE E.company_id = C.company_id

Some naming and coding standards for PL/SQL – DRAFT – Page 25

Page 26: Enterprise Naming and Coding Standards€¦  · Web viewFile naming conventions 3. Identifier naming conventions 4. Scope 4. Type 4. Primary Identifier 5. Modifier 5. Suffix 5. Variable

AND E.employee_id = SH.employee_id

AND E.hire_date > ADD_MONTHS (SYSDATE, -60);

UPDATE employee

SET hire_date = SYSDATE

Termination_date = NULL

WHERE department_id = 105;

Use sensible abbreviations for table and column aliasesInstead of a code segment such as,

SELECT … select list …

FROM employee A

Company B

History C

Bonus D

Profile E

Sales F

WHERE A.company_id = B.company_id

AND A.employee_id = C.employee_id

AND B.company_id = F.company_id

AND A.employee_id = D.employee_id

AND B.company_id = E.company_id;

Use a code segment such as,

SELECT … select list …

FROM employee EMP

Company CO

History HIST

Bonus

Profile PROF

Sales

WHERE EMP.company_id = CO.company_id

AND EMP.employee_id = HIST.employee_id

AND CO.company_id = SALES.company_id

AND EMP.employee_id = BONUS.employee_id

AND CO.company_id = PROF.company_id;

Some naming and coding standards for PL/SQL – DRAFT – Page 26