Some Naming and Coding Standards

Size: px
Start display at page:

Download "Some Naming and Coding Standards"

Transcription

1 Some Naming and Coding Standards April 25, 2000 **DRAFT ** 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

2 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 Formatting Multiline Statements Commenting style Comment As you Code Explain Why - Not the How Make Comments Easy to Enter and Maintain Maintain Indentation Syntax Guidelines Branching and Labels Conditional Statements REPETITION Avoid Unstructured Exits from Loops Do not use PL/SQL where you can use a SQL statement instead PL/Sql Programming Guidelines Use Named Constants to Avoid Hard-coding Values Convert Variables into Named Constants Avoid the recycling of variables Name Subtypes to Self-document Code Remove Unused Variables from Programs Use %TYPE when a variable represents a column...19 Use %TYPE to standardize non-database declarations Use Variables to hide complex logic Building from high-level rules Converting pseudo-code to PL/SQL SQL Guidelines Right align the reserved words Don t skimp on line seperators Use sensible abbreviations for table and column aliases Some naming and coding standards for PL/SQL DRAFT Page 2

3 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 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 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 Extension Example Stored Package Body pkb dbmsout.pkb Some naming and coding standards for PL/SQL DRAFT Page 3

4 Stored Package Specification pks dbmsout.pks Stored Procedure spr UpdCust.spr Stored Function sfn GetCust.sfn Trigger trg cascade.trg Anonymous block sql testtrg.sql Table creation statement tab emp.tab Test script tst dbmssql.tst Multiple DDL statements ddl 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 Description Example g Global g_temp l Local l_temp p Parameter 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 Description Example Comment c Constant gc_loop_count Global constant c Constant lc_loop_count Local Constant. c Constant pc_loop_count Parameter v Variable gv_loop_count Global Variable v Variable lv_loop_count Local Variable v 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 Example cur Cursor gcur_employee vcr Cursor(variable) lvcr_employee tbl Table gtbl_employee rec Record ltrec_address Some naming and coding standards for PL/SQL DRAFT Page 4

5 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 Example typ TYPE gtyp_new_account_table stp SUBTYPE 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 Modifier Position Variable address mailing Precede mailing_address phone home Precede home_phone customer_name last Middle 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 Description Example i Input only parameter pv_num_items_i o Output only parameter pv_sum_o io 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

6 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 Type Primary Identifier Modifier Suffix Example Local cur Account New Null lcur_new_account Parameter 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 Example Local rec Account Null lrec_account Parameter rec Account IN prec_account_i Global 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 Example Local rec Account newest Null lrec_new_account Parameter rec Account duplicate IN prec_duplicate_account_i Global 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 Example Local v year idx lv_year_idx FOR lv_year_idx IN 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

7 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 Example Local typ Account new table ltyp_new_account_table Global 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 Example Local tbl Account new ltbl_new_account Global 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 Example Local stp Primary_key lstp_primary_key Global stp Large_string gstp_large_string SUBTYPE lstp_primary_key IS BINARY_INTEGER; SUBTYPE gstp_large_string IS VARCHAR2; PL/SQL Record TYPE Some naming and coding standards for PL/SQL DRAFT Page 7

8 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 Example Local typ Account new record ltyp_new_account_record Global 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 Example Local rec Account new ltyp_new_account_record Global rec Account old 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 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. Indentation Indentation 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) 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. Some naming and coding standards for PL/SQL DRAFT Page 8

9 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. 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. lv_var1 := 0 ; lv_var2 := 1 ; lv_var1 := 0 ; lv_var2 := 1 ; -- This is valid -- But code this -- way instead. Use white space inside a statement. Always include a space between an identifier and a separator. Some naming and coding standards for PL/SQL DRAFT Page 9

10 lv_var1:=0; lv_var1 := 0 ; -- This is valid -- 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 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 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 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 LOOP Lv_first_month.. lv_last_month -- the IN statement needs its -- range gv_q1_sales := lv_month1_sales + +. lv_month2_sales + lv_month3_sales; -- An assignment cannot end with a Gen_stats Some naming and coding standards for PL/SQL DRAFT Page 10

11 (pv_company_id, pv_last_year_date, -- Last comma indicates pv_rollup_type, pv_total) ; -- other parameters to follow. 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. 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 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 gotos We 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 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. Some naming and coding standards for PL/SQL DRAFT Page 11

12 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,, 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> IF <condition1>... ELSE ELSIF <Condition2> IF <Condition2> ELSIF <Condition3> ELSE IF <Condition3> ELSIF <Condition4> ELSE IF <Condition4> Flat 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 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 IF condition B Some naming and coding standards for PL/SQL DRAFT Page 12

13 ... 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. IF sal BETWEEN 0 AND ELSIF sal BETWEEN AND ELSIF sal BETWEEN AND 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. IF total_sal BETWEEN AND AND emp_status (emp_rec.empno) = 'N' AND (MONTHS_BETWEEN (emp_rec.hiredate, SYSDATE) > 10) give_raise (emp_rec.empno); IF eligible_for_raise (emp_rec.empno) give_raise (emp_rec.empno); Some naming and coding standards for PL/SQL DRAFT Page 13

14 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 date_in_past := TRUE; ELSE date_in_past := FALSE; With this: date_in_past := hiredate < SYSDATE; 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 WHILE...LOOP is as follows: WHILE condition LOOP Statements END LOOP spaces. Again keep all the keywords in the same column, while indenting the keyword columns by 3 Some naming and coding standards for PL/SQL DRAFT Page 14

15 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 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 times PL/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_value LOOP statements END LOOP; Cursor For Loop FOR lv_record_index IN my_cursor LOOP statements END LOOP; Again notice that the indentation is consistent at 3 spaces. Never Declare the FOR Loop Index FOR year_ind IN LOOP calc_profits (year_ind); END LOOP; Some naming and coding standards for PL/SQL DRAFT Page 15

16 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' give_raise (emp_rec.empno, ); END; Suppose you need the value of the loop index (year_count in the following example) for debugging: DECLARE year_count INTEGER := NULL; BEGIN FOR year_count IN LOOP calc_pnl (year_count); END LOOP; Some naming and coding standards for PL/SQL DRAFT Page 16

17 EXCEPTION WHEN NO_DATA_FOUND 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 LOOP my_count := year_count; calc_pnl (year_count); END LOOP; EXCEPTION WHEN NO_DATA_FOUND 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. 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 Some naming and coding standards for PL/SQL DRAFT Page 17

18 FOR year_count IN 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. 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. Some naming and coding standards for PL/SQL DRAFT Page 18

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

20 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 BEGIN END; first_name customer.cust_fname%type; last_name address city customer.cust_lname%type; customer.cust_addr_l1%type; customer.cust_city%type; state customer.cust_state_abbrev_cd%type; soc_sec# customer.cust_soc_sec_number%type;... interact with database customer information... 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: DECLARE revenue_data NUMBER(20,2); 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. Some naming and coding standards for PL/SQL DRAFT Page 20

21 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 cust_priority_type = 'HIGH' AND order_status = 'O' ship_order ('EXPRESS'); ELSIF (order_date >= ADD_MONTHS (SYSDATE, -2) OR ADD_MONTHS (SYSDATE, 3) > shipdate) AND order_status = 'O' ship_order ('GROUND'); Some naming and coding standards for PL/SQL DRAFT Page 21

22 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 ELSE IF customer-priority-is-high ELSE ship-express; ship-ground; ship-ground; The next step would be to rewrite this nested IF statement as follows: IF order-overdue AND IF customer-priority-is-high ELSE ship-express; ship-ground; Some naming and coding standards for PL/SQL DRAFT Page 22

23 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 END; IF order_overdue AND high_priority ship_order ('EXPRESS'); ELSE ship_order ('GROUND'); 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." 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 Some naming and coding standards for PL/SQL DRAFT Page 23

24 DEFAULT cust_priority_type = 'HIGH'; BEGIN END; IF order_overdue AND high_priority ship_order ('EXPRESS'); ELSE ship_order ('GROUND'); 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- 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. SQL Guidelines Right align the reserved words Select Insert Update SELECT last_name, first_name FROM employee WHERE department_id = 15 AND hire_date < SYSDATE; INSERT INTO employee (employee_id, ) VALUES (105, ); UPDATE employee SET hire_date = SYSDATE Some naming and coding standards for PL/SQL DRAFT Page 24

25 WHERE hire_date IS NULL AND termination_date IS NULL Delete DELETE FROM employee WHERE department_id = 15; Don t 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 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 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 aliases Instead 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; Some naming and coding standards for PL/SQL DRAFT Page 25

26 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

Oracle PL/SQL Best Practices

Oracle PL/SQL Best Practices Achieving PL/SQL Excellence Oracle PL/SQL Best Practices Steven Feuerstein Me - www.stevenfeuerstein.com PL/Solutions - www.plsolutions.com RevealNet - www.revealnet.com 7/5/99 Copyright 1999 Steven Feuerstein

More information

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

PL/SQL Overview. Basic Structure and Syntax of PL/SQL PL/SQL Overview PL/SQL is Procedural Language extension to SQL. It is loosely based on Ada (a variant of Pascal developed for the US Dept of Defense). PL/SQL was first released in ١٩٩٢ as an optional extension

More information

PL / SQL Basics. Chapter 3

PL / SQL Basics. Chapter 3 PL / SQL Basics Chapter 3 PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2 PL / SQL Block Basic

More information

Writing Control Structures

Writing Control Structures Writing Control Structures Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 5-1 Objectives After completing this lesson, you should be able to do the following: Identify

More information

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement Objectives After completing this lesson, you should be able to do the following: List the capabilities of SQL SELECT statements Execute a basic SELECT statement

More information

Oracle Internal & Oracle Academy

Oracle Internal & Oracle Academy Declaring PL/SQL Variables Objectives After completing this lesson, you should be able to do the following: Identify valid and invalid identifiers List the uses of variables Declare and initialize variables

More information

SQL Server Database Coding Standards and Guidelines

SQL Server Database Coding Standards and Guidelines SQL Server Database Coding Standards and Guidelines http://www.sqlauthority.com Naming Tables: Stored Procs: Triggers: Indexes: Primary Keys: Foreign Keys: Defaults: Columns: General Rules: Rules: Pascal

More information

OPP 2007. ODTUG Kaleidoscope. An ODTUG SP* Oracle PL/SQL Programming Conference. WOW-Wide Open World, Wide Open Web!

OPP 2007. ODTUG Kaleidoscope. An ODTUG SP* Oracle PL/SQL Programming Conference. WOW-Wide Open World, Wide Open Web! OPP 2007 February 28 March 1, 2007 San Mateo Marriott San Mateo, California An ODTUG SP* Oracle PL/SQL Programming Conference *SP Seriously Practical Conference ODTUG Kaleidoscope June 18 21, 2007 Pre-conference

More information

Hypercosm. Studio. www.hypercosm.com

Hypercosm. Studio. www.hypercosm.com Hypercosm Studio www.hypercosm.com Hypercosm Studio Guide 3 Revision: November 2005 Copyright 2005 Hypercosm LLC All rights reserved. Hypercosm, OMAR, Hypercosm 3D Player, and Hypercosm Studio are trademarks

More information

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer. Test: Final Exam Semester 1 Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer. Section 6 1. The following code does not violate any constraints and will

More information

Making the Most of Oracle PL/SQL Error Management Features

Making the Most of Oracle PL/SQL Error Management Features Making the Most of Oracle PL/SQL Error Management Features Copyright 2000-2008 Steven Feuerstein - Page 1 Steven Feuerstein PL/SQL Evangelist Quest Software steven.feuerstein@quest.com So...why listen

More information

14 Triggers / Embedded SQL

14 Triggers / Embedded SQL 14 Triggers / Embedded SQL COMS20700 Databases Dr. Essam Ghadafi TRIGGERS A trigger is a procedure that is executed automatically whenever a specific event occurs. You can use triggers to enforce constraints

More information

Introduction to Python

Introduction to Python WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language

More information

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals Oracle University Contact Us: 1.800.529.0165 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This course is designed to deliver the fundamentals of SQL and PL/SQL along

More information

Physical Design. Meeting the needs of the users is the gold standard against which we measure our success in creating a database.

Physical Design. Meeting the needs of the users is the gold standard against which we measure our success in creating a database. Physical Design Physical Database Design (Defined): Process of producing a description of the implementation of the database on secondary storage; it describes the base relations, file organizations, and

More information

The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings

The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings Object Calisthenics 9 steps to better software design today, by Jeff Bay http://www.xpteam.com/jeff/writings/objectcalisthenics.rtf http://www.pragprog.com/titles/twa/thoughtworks-anthology We ve all seen

More information

Consulting. Personal Attention, Expert Assistance

Consulting. Personal Attention, Expert Assistance Consulting Personal Attention, Expert Assistance 1 Writing Better SQL Making your scripts more: Readable, Portable, & Easily Changed 2006 Alpha-G Consulting, LLC All rights reserved. 2 Before Spending

More information

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals NEW Oracle University Contact Us: + 38516306373 Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training delivers the

More information

Handling Exceptions. Copyright 2008, Oracle. All rights reserved.

Handling Exceptions. Copyright 2008, Oracle. All rights reserved. Handling Exceptions Handling Exceptions What Will I Learn? In this lesson, you will learn to: Describe several advantages of including exception handling code in PL/SQL Describe the purpose of an EXCEPTION

More information

Guide to Performance and Tuning: Query Performance and Sampled Selectivity

Guide to Performance and Tuning: Query Performance and Sampled Selectivity Guide to Performance and Tuning: Query Performance and Sampled Selectivity A feature of Oracle Rdb By Claude Proteau Oracle Rdb Relational Technology Group Oracle Corporation 1 Oracle Rdb Journal Sampled

More information

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1 Handling Exceptions Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1 Objectives After completing this lesson, you should be able to do the following: Define PL/SQL

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

Database Programming with PL/SQL: Learning Objectives

Database Programming with PL/SQL: Learning Objectives Database Programming with PL/SQL: Learning Objectives This course covers PL/SQL, a procedural language extension to SQL. Through an innovative project-based approach, students learn procedural logic constructs

More information

An Introduction to PL/SQL. Mehdi Azarmi

An Introduction to PL/SQL. Mehdi Azarmi 1 An Introduction to PL/SQL Mehdi Azarmi 2 Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database language. Combines power and flexibility of SQL (4GL)

More information

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks 1 Stored Procedures in PL/SQL Many modern databases support a more procedural approach to databases they allow you to write procedural code to work with data. Usually, it takes the form of SQL interweaved

More information

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals Oracle University Contact Us: +966 12 739 894 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training is designed to

More information

Error Management in Oracle PL/SQL

Error Management in Oracle PL/SQL Fast Track PL/SQL Error Management in Oracle PL/SQL Steven Feuerstein PL/SQL Evangelist, Quest Software steven.feuerstein@quest.com PL/SQL Obsession - www.toadworld.com/sf Copyright 2000-2008 Steven Feuerstein

More information

Oracle PL/SQL Language. CIS 331: Introduction to Database Systems

Oracle PL/SQL Language. CIS 331: Introduction to Database Systems Oracle PL/SQL Language CIS 331: Introduction to Database Systems Topics: Structure of a PL/SQL program Exceptions 3-valued logic Loops (unconditional, while, for) Cursors Procedures Functions Triggers

More information

Introduction to PL/SQL Programming

Introduction to PL/SQL Programming Introduction to PL/SQL Programming Introduction to PL/SQL Programming i-ii Introduction to PL/SQL Programming 1997-2001 Technology Framers, LLC Introduction to PL/SQL Programming This publication is protected

More information

Darshan Institute of Engineering & Technology PL_SQL

Darshan Institute of Engineering & Technology PL_SQL Explain the advantages of PL/SQL. Advantages of PL/SQL Block structure: PL/SQL consist of block of code, which can be nested within each other. Each block forms a unit of a task or a logical module. PL/SQL

More information

2 SQL in iseries Navigator

2 SQL in iseries Navigator 2 SQL in iseries Navigator In V4R4, IBM added an SQL scripting tool to the standard features included within iseries Navigator and has continued enhancing it in subsequent releases. Because standard features

More information

PL/SQL MOCK TEST PL/SQL MOCK TEST I

PL/SQL MOCK TEST PL/SQL MOCK TEST I http://www.tutorialspoint.com PL/SQL MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to PL/SQL. You can download these sample mock tests at your local

More information

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer. est: Final Exam Semester 1 Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer. Section 6 1. How can you retrieve the error code and error message of any

More information

Answers to the Try It Yourself Sections

Answers to the Try It Yourself Sections APPENDIX D Answers to the Try It Yourself Sections Chapter 1, PL/SQL Concepts 1) To calculate the area of a circle, you must square the circle s radius and then multiply it by π. Write a program that calculates

More information

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT INTRODUCTION: Course Objectives I-2 About PL/SQL I-3 PL/SQL Environment I-4 Benefits of PL/SQL I-5 Benefits of Subprograms I-10 Invoking Stored Procedures

More information

STUDY OF PL/SQL BLOCK AIM: To Study about PL/SQL block.

STUDY OF PL/SQL BLOCK AIM: To Study about PL/SQL block. Ex.No.6 STUDY OF PL/SQL BLOCK AIM: To Study about PL/SQL block. DESCRIPTION: PL/SQL PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural features

More information

Intro to Embedded SQL Programming for ILE RPG Developers

Intro to Embedded SQL Programming for ILE RPG Developers Intro to Embedded SQL Programming for ILE RPG Developers Dan Cruikshank DB2 for i Center of Excellence 1 Agenda Reasons for using Embedded SQL Getting started with Embedded SQL Using Host Variables Using

More information

Database Design Standards. U.S. Small Business Administration Office of the Chief Information Officer Office of Information Systems Support

Database Design Standards. U.S. Small Business Administration Office of the Chief Information Officer Office of Information Systems Support Database Design Standards U.S. Small Business Administration Office of the Chief Information Officer Office of Information Systems Support TABLE OF CONTENTS CHAPTER PAGE NO 1. Standards and Conventions

More information

Oracle SQL. Course Summary. Duration. Objectives

Oracle SQL. Course Summary. Duration. Objectives Oracle SQL Course Summary Identify the major structural components of the Oracle Database 11g Create reports of aggregated data Write SELECT statements that include queries Retrieve row and column data

More information

Module 10. Coding and Testing. Version 2 CSE IIT, Kharagpur

Module 10. Coding and Testing. Version 2 CSE IIT, Kharagpur Module 10 Coding and Testing Lesson 23 Code Review Specific Instructional Objectives At the end of this lesson the student would be able to: Identify the necessity of coding standards. Differentiate between

More information

Creating PL/SQL Blocks. Copyright 2007, Oracle. All rights reserved.

Creating PL/SQL Blocks. Copyright 2007, Oracle. All rights reserved. What Will I Learn? In this lesson, you will learn to: Describe the structure of a PL/SQL block Identify the different types of PL/SQL blocks Identify PL/SQL programming environments Create and execute

More information

Oracle PL/SQL Programming

Oracle PL/SQL Programming FOURTH EDITION Oracle PL/SQL Programming Steven Feuerstein with Bill Pribvl O'REILLY' Beijing Cambridge Farnham Köln Paris Sebastopol Taipei Tokyo Table of Contents Preface xiii Part 1. Programming in

More information

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0 VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 UX Software - 2009 TABLE OF CONTENTS INTRODUCTION... ii What is this book about?... iii How to use this book... iii Time to start...

More information

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff D80198GC10 Oracle Database 12c SQL and Fundamentals Summary Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff Level Professional Delivery Method Instructor-led

More information

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query Objectives The objective of this lab is to learn the query language of SQL. Outcomes After completing this Lab,

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

TOP TWENTY PL/SQL TIPS AND TECHNIQUES

TOP TWENTY PL/SQL TIPS AND TECHNIQUES TOP TWENTY PL/SQL TIPS AND TECHNIQUES STEVEN FEUERSTEIN Copyright 1996 Oracle User Resource, Inc. Adirondak Information Resources PL/SQL has come a long way since its rather simplistic beginnings as a

More information

Programming with SQL

Programming with SQL Unit 43: Programming with SQL Learning Outcomes A candidate following a programme of learning leading to this unit will be able to: Create queries to retrieve information from relational databases using

More information

Page 1 of 7 Welcome brendan ( Account Help Sign Out ) United States Communities I am a... I want to... Secure Search Products and Services Solutions Downloads Store Support Training Partners About Oracle

More information

Programming Database lectures for mathema

Programming Database lectures for mathema Programming Database lectures for mathematics students April 25, 2015 Functions Functions are defined in Postgres with CREATE FUNCTION name(parameter type,...) RETURNS result-type AS $$ function-body $$

More information

SPECIFICATION BY EXAMPLE. Gojko Adzic. How successful teams deliver the right software. MANNING Shelter Island

SPECIFICATION BY EXAMPLE. Gojko Adzic. How successful teams deliver the right software. MANNING Shelter Island SPECIFICATION BY EXAMPLE How successful teams deliver the right software Gojko Adzic MANNING Shelter Island Brief Contents 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Preface xiii Acknowledgments xxii

More information

Handling Exceptions. Schedule: Timing Topic 45 minutes Lecture 20 minutes Practice 65 minutes Total

Handling Exceptions. Schedule: Timing Topic 45 minutes Lecture 20 minutes Practice 65 minutes Total Handling Exceptions Schedule: Timing Topic 45 minutes Lecture 20 minutes Practice 65 minutes Total Objectives After completing this lesson, you should be able to do the following: Define PL/SQL exceptions

More information

Chapter 13: Program Development and Programming Languages

Chapter 13: Program Development and Programming Languages Understanding Computers Today and Tomorrow 12 th Edition Chapter 13: Program Development and Programming Languages Learning Objectives Understand the differences between structured programming, object-oriented

More information

JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved.

JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved. 1 6 JavaScript: Introduction to Scripting 2 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask,

More information

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA www.sybex.com

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA www.sybex.com Essential SQL 2 Essential SQL This bonus chapter is provided with Mastering Delphi 6. It is a basic introduction to SQL to accompany Chapter 14, Client/Server Programming. RDBMS packages are generally

More information

Embedded SQL programming

Embedded SQL programming Embedded SQL programming http://www-136.ibm.com/developerworks/db2 Table of contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Before

More information

Training Guide. PL/SQL for Beginners. Workbook

Training Guide. PL/SQL for Beginners. Workbook An Training Guide PL/SQL for Beginners Workbook Workbook This workbook should be worked through with the associated Training Guide, PL/SQL for Beginners. Each section of the workbook corresponds to a section

More information

Memory Systems. Static Random Access Memory (SRAM) Cell

Memory Systems. Static Random Access Memory (SRAM) Cell Memory Systems This chapter begins the discussion of memory systems from the implementation of a single bit. The architecture of memory chips is then constructed using arrays of bit implementations coupled

More information

COMS20700 DATABASES 13 PL/SQL. COMS20700 Databases Dr. Essam Ghadafi

COMS20700 DATABASES 13 PL/SQL. COMS20700 Databases Dr. Essam Ghadafi 13 PL/SQL COMS20700 Databases Dr. Essam Ghadafi PL/SQL - OVERVIEW PL/SQL: Procedure Language/Structured Query Language. Provides programming languages features: IF, Loops, subroutines,... Code can be compiled

More information

Conditionals: (Coding with Cards)

Conditionals: (Coding with Cards) 10 LESSON NAME: Conditionals: (Coding with Cards) Lesson time: 45 60 Minutes : Prep time: 2 Minutes Main Goal: This lesson will introduce conditionals, especially as they pertain to loops and if statements.

More information

GET DATA FROM MULTIPLE TABLES QUESTIONS

GET DATA FROM MULTIPLE TABLES QUESTIONS GET DATA FROM MULTIPLE TABLES QUESTIONS http://www.tutorialspoint.com/sql_certificate/get_data_from_multiple_tables_questions.htm Copyright tutorialspoint.com 1.Which of the following is not related to

More information

6. Control Structures

6. Control Structures - 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

More information

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals NEW Oracle University Contact Us: 001-855-844-3881 & 001-800-514-06-97 Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals

More information

PGR Computing Programming Skills

PGR Computing Programming Skills PGR Computing Programming Skills Dr. I. Hawke 2008 1 Introduction The purpose of computing is to do something faster, more efficiently and more reliably than you could as a human do it. One obvious point

More information

PL/SQL Practicum #2: Assertions, Exceptions and Module Stability

PL/SQL Practicum #2: Assertions, Exceptions and Module Stability PL/SQL Practicum #2: Assertions, Exceptions and Module Stability John Beresniewicz Technology Manager Precise Software Solutions Agenda Design by Contract Assertions Exceptions Modular Code DESIGN BY CONTRACT

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

An Introduction to the WEB Style of Literate Programming

An Introduction to the WEB Style of Literate Programming An Introduction to the WEB Style of Literate Programming Literate Programming by Bart Childs One of the greatest needs in computing is the reduction of the cost of maintenance of codes. Maintenance programmers

More information

Oracle Database 12c: Introduction to SQL Ed 1.1

Oracle Database 12c: Introduction to SQL Ed 1.1 Oracle University Contact Us: 1.800.529.0165 Oracle Database 12c: Introduction to SQL Ed 1.1 Duration: 5 Days What you will learn This Oracle Database: Introduction to SQL training helps you write subqueries,

More information

Oracle Database 10g: Introduction to SQL

Oracle Database 10g: Introduction to SQL Oracle University Contact Us: 1.800.529.0165 Oracle Database 10g: Introduction to SQL Duration: 5 Days What you will learn This course offers students an introduction to Oracle Database 10g database technology.

More information

The programming language C. sws1 1

The programming language C. sws1 1 The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

More information

(Refer Slide Time 00:56)

(Refer Slide Time 00:56) Software Engineering Prof.N. L. Sarda Computer Science & Engineering Indian Institute of Technology, Bombay Lecture-12 Data Modelling- ER diagrams, Mapping to relational model (Part -II) We will continue

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Flowchart Techniques

Flowchart Techniques C H A P T E R 1 Flowchart Techniques 1.1 Programming Aids Programmers use different kinds of tools or aids which help them in developing programs faster and better. Such aids are studied in the following

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition Chapter 2: Algorithm Discovery and Design Invitation to Computer Science, C++ Version, Third Edition Objectives In this chapter, you will learn about: Representing algorithms Examples of algorithmic problem

More information

Software Engineering Techniques

Software Engineering Techniques Software Engineering Techniques Low level design issues for programming-in-the-large. Software Quality Design by contract Pre- and post conditions Class invariants Ten do Ten do nots Another type of summary

More information

Netezza SQL Class Outline

Netezza SQL Class Outline Netezza SQL Class Outline CoffingDW education has been customized for every customer for the past 20 years. Our classes can be taught either on site or remotely via the internet. Education Contact: John

More information

Performance Tuning for the Teradata Database

Performance Tuning for the Teradata Database Performance Tuning for the Teradata Database Matthew W Froemsdorf Teradata Partner Engineering and Technical Consulting - i - Document Changes Rev. Date Section Comment 1.0 2010-10-26 All Initial document

More information

Parsing Technology and its role in Legacy Modernization. A Metaware White Paper

Parsing Technology and its role in Legacy Modernization. A Metaware White Paper Parsing Technology and its role in Legacy Modernization A Metaware White Paper 1 INTRODUCTION In the two last decades there has been an explosion of interest in software tools that can automate key tasks

More information

Introduction to SQL for Data Scientists

Introduction to SQL for Data Scientists Introduction to SQL for Data Scientists Ben O. Smith College of Business Administration University of Nebraska at Omaha Learning Objectives By the end of this document you will learn: 1. How to perform

More information

JavaScript: Control Statements I

JavaScript: Control Statements I 1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

More information

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

More information

Displaying Data from Multiple Tables

Displaying Data from Multiple Tables 4 Displaying Data from Multiple Tables Copyright Oracle Corporation, 2001. All rights reserved. Schedule: Timing Topic 55 minutes Lecture 55 minutes Practice 110 minutes Total Objectives After completing

More information

Maintaining Stored Procedures in Database Application

Maintaining Stored Procedures in Database Application Maintaining Stored Procedures in Database Application Santosh Kakade 1, Rohan Thakare 2, Bhushan Sapare 3, Dr. B.B. Meshram 4 Computer Department VJTI, Mumbai 1,2,3. Head of Computer Department VJTI, Mumbai

More information

Outline. 1 Denitions. 2 Principles. 4 Implementation and Evaluation. 5 Debugging. 6 References

Outline. 1 Denitions. 2 Principles. 4 Implementation and Evaluation. 5 Debugging. 6 References Outline Computer Science 331 Introduction to Testing of Programs Mike Jacobson Department of Computer Science University of Calgary Lecture #3-4 1 Denitions 2 3 4 Implementation and Evaluation 5 Debugging

More information

Coding Therapy for Software Developers

Coding Therapy for Software Developers Coding Therapy for Software Developers Steven Feuerstein PL/SQL Evangelist, Dell steven@stevenfeuerstein.com I am not making light of therapy Therapy can be a very important and meaningful process for

More information

PloneSurvey User Guide (draft 3)

PloneSurvey User Guide (draft 3) - 1 - PloneSurvey User Guide (draft 3) This short document will hopefully contain enough information to allow people to begin creating simple surveys using the new Plone online survey tool. Caveat PloneSurvey

More information

Handling PL/SQL Errors

Handling PL/SQL Errors Handling PL/SQL Errors In PL/SQL, a warning or error condition is called an exception. Exceptions can be internally defined (by the run-time system) or user defined. Examples of internally defined exceptions

More information

Introduction. SQL Developer Data Modeler Overview. The Reporting Schema. SQL Developer Data Modeler 3.0 Under The Covers: The Reporting Schema

Introduction. SQL Developer Data Modeler Overview. The Reporting Schema. SQL Developer Data Modeler 3.0 Under The Covers: The Reporting Schema SQL Developer Data Modeler 3.0 Under The Covers: The Reporting Schema Marc de Oliveira, Simplify Systems Introduction This article will show you how I have used the SQL Developer Data Modeler (SDDM) Reporting

More information

EMC Publishing. Ontario Curriculum Computer and Information Science Grade 11

EMC Publishing. Ontario Curriculum Computer and Information Science Grade 11 EMC Publishing Ontario Curriculum Computer and Information Science Grade 11 Correlations for: An Introduction to Programming Using Microsoft Visual Basic 2005 Theory and Foundation Overall Expectations

More information

CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions CS 2112 Spring 2014 Assignment 3 Data Structures and Web Filtering Due: March 4, 2014 11:59 PM Implementing spam blacklists and web filters requires matching candidate domain names and URLs very rapidly

More information

Visual Logic Instructions and Assignments

Visual Logic Instructions and Assignments Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.

More information

Data Modeling Basics

Data Modeling Basics Information Technology Standard Commonwealth of Pennsylvania Governor's Office of Administration/Office for Information Technology STD Number: STD-INF003B STD Title: Data Modeling Basics Issued by: Deputy

More information

Once the schema has been designed, it can be implemented in the RDBMS.

Once the schema has been designed, it can be implemented in the RDBMS. 2. Creating a database Designing the database schema... 1 Representing Classes, Attributes and Objects... 2 Data types... 5 Additional constraints... 6 Choosing the right fields... 7 Implementing a table

More information

DECLARATION SECTION. BODY STATEMENTS... Required

DECLARATION SECTION. BODY STATEMENTS... Required 1 EXCEPTION DECLARATION SECTION Optional BODY STATEMENTS... Required STATEMENTS Optional The above Construction is called PL/SQL BLOCK DATATYPES 2 Binary Integer (-2 **31-1,2**31+1) signed integer fastest

More information

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction AppendixA1A1 Java Language Coding Guidelines A1.1 Introduction This coding style guide is a simplified version of one that has been used with good success both in industrial practice and for college courses.

More information

A basic create statement for a simple student table would look like the following.

A basic create statement for a simple student table would look like the following. Creating Tables A basic create statement for a simple student table would look like the following. create table Student (SID varchar(10), FirstName varchar(30), LastName varchar(30), EmailAddress varchar(30));

More information

Instant SQL Programming

Instant SQL Programming Instant SQL Programming Joe Celko Wrox Press Ltd. INSTANT Table of Contents Introduction 1 What Can SQL Do for Me? 2 Who Should Use This Book? 2 How To Use This Book 3 What You Should Know 3 Conventions

More information