Wednesday, January 5, 2011

Cobol Coding Standards

1.         COBOL STANDARDS

The following standards can be followed while coding COBOL programs.  

1.1     General

·         Comments should be used at the start of the procedure division to give a general overview of the program and should also be used throughout the program to explain the reasons for processing.
·         Use of limited blank lines must be made throughout the program to improve readability.
·         All Warnings issued during compilation of the COBOL program must be investigated and eliminated, if possible.
·         Changes to existing programs/common modules are written in the same style as the original code.

1.2    Identification Division

·         This must consist of at least the following entries:

          PROGRAM-ID  
          AUTHOR     
          INSTALLATION
          DATE-WRITTEN
          DATE-COMPILED

·         The PROGRAM-ID should be same as the program name.
·         At the end of the Division there must be a summary description of the program and its modification history.   
·         For new programs give just heading lines for modification history.
·         Give the details of input and output files, copybooks being used in the program.




1.3     Environment Division.

·         File Status must be used for all files.
·         Select statements in the File-Control are in the same order as the corresponding FDs in the File Section of the Data Division.
·         Each clause on the SELECT statement should start on a separate line.
·         File names can have prefix  ‘I’ for input files and ‘O’ for output files. The order of select statements for the files can be input files, then updated files and then output files.

Ex.     SELECT I-FILE  ASSIGN TO DD1
          SELECT O-FILE ASSIGN TO DD2


1.4     Data Division

·         FD must be preceded by a blank line with ‘*’ in column 7.
·         Proper and meaningful names must be used for data names.
·         Level numbers within the division must begin with '01' in column 8 and indented 4 columns to the right for each increase in number. The subsequent levels must be '05', '10' etc.
·         Clauses must all be column-aligned and begin after column 34 using a separate line from the field name if necessary.
·         PIC clause must be in column 40.If the field name goes beyond 38, PIC must start from column 40 of the next line.
·         It is recommended that signed packed decimal (COMP-3) fields are used for numeric items that are used in arithmetic operations. It is also recommended that COMP fields are used for indexing.



1.4.1 File Section

·         FD entries must occur in the same order as their corresponding SELECT statement in the Environment Division.
·         Copybooks should be used for file layouts (If applicable).
·         Record layouts must follow a standard convention that will enable a particular record or element to be easily cross-referenced.

1.4.2 Working-Storage Section 

·         The Working Storage must be preceded by  an ’eye-catcher’ of the format:
              77  FILLER                      PIC X(32) VALUE
                                   'START PNB0412B WORKING STORAGE'.
·         The following code must be used in the program 
     01 PGM-INFO.                                                 
          03  FILLER                     PIC X(09) VALUE 'PROGRAM:'.          
          03  PGM-ID                     PIC X(08) VALUE 'program name'.          
          03  FILLER                               PIC X(10) VALUE '  VERSION:'.        
          03  PGM-VERSION        PIC X(02) VALUE '01'.                
          03  FILLER                               PIC X(30) VALUE   '  LAST COMPILE TIME AND DATE:'.
          03  PGM-COMPILED     PIC X(8).                            
         
     And in Procedure Division have the following statements executed first
                     MOVE WHEN-COMPILED TO PGM-COMPILED OF PGM-INFO
                     DISPLAY PGM-INFO
·         Data names within Working-Storage must be prefixed by WS.
·           Like data items must be defined together and given the same prefix. And in grouping, the fields should be declared in alphabetical order as far as possible.
       e.g. all Dates, Counters , Constants , Flags, Index, PARMs and all print fields etc.
·         Each group must be preceded by a comment.
·         If a data element in Working-storage corresponds to a data element in the File Section then the only difference in their names must be the prefix.
·         All constants/pre-set literals must be defined with the value clause (e.g. messages, headings etc).
·         If a variable whose value changes during program execution needs an initial value, move the value in the INITIALIZE paragraph in Procedure Division rather than using a value clause in the working storage section.
·         Processing will be made easier to follow if counters, totals, subscripts etc are initialized before use.
·         88 Levels should be used to clarify procedure code. They must be indented from their corresponding variable and must have the same prefix.
·         Database variables (ALL INCLUDE statements)  must be declared at the end of the working storage section each  preceded by a  comment containing a brief description.

·         The working storage section must be ended with an eye-catcher of the format

                         01  FILLER                                        PIC X(40)
                                                           VALUE 'END <program name> WORKING STORAGE'.

1.4.3 Linkage Section

·         The data name must be the same as the corresponding data name in the calling module.

1.5     Procedure Division 

The following are the general standards to be observed when coding the Procedure Division:

·         The first section of the program must be named similar to 0000-MAIN-PARA .
·         The format of the 0000-MAIN-PARA section should be as follows:-

             PERFORM 1000-INIT-PARA                      THRU 1000-EXIT.
             PERFORM 2000-PROCESS-PARA            THRU 2000-EXIT.
             PERFORM 9000-TERMINATE-PARA        THRU 9000-EXIT .
             STOP RUN.

·         OPEN/CLOSE one file at a time. Always check for the file status after each file is accessed.
·         Always Check SQLCODE after executing an SQL statement.
·         There should be a standard ERROR paragraph, which will take care of all error processing. As soon as an error is detected (for e.g., OPEN failure, READ failure, WRITE failure etc) appropriate error variables must be set and control transferred to the ERROR paragraph.
·         This ERROR paragraph will pass the necessary information to the Error-handling routine which will generate the error report, set a return-code or abend the program depending on severity of error .

·         Blank lines must be used to break up the code and improve readability. For example, before and after the outermost IF statements, PERFORM statements etc.

·         IF statements must check for the most likely occurrence first, where possible.

·         All IF statements should be clearly understandable (indented, no double negatives).
      Code ELSE statement alone on a separate line.

·         All EVALUATE statements should contain ‘WHEN OTHER’.

·         Explicit terminators must be used for IF statements (i.e.) END-IF must be used. In-line PERFORMS must be terminated with the corresponding END-PERFORM statement. If EVALUATE statements are used, they must have a corresponding END-EVALUATE

·         Preferably, all ‘TO’ in MOVE and SET statements must be at column 40. If this is not possible, within a paragraph the TO clause must be aligned.

·          Periods must not be used unless necessary. Only one period just before the end of each paragraph must be coded. Periods must be on separate line and nothing else must be on the line.

·         Avoid using GO TO. A forward GOTO to the corresponding EXIT paragraph can be used. Also it can be used when its use will significantly simplify the coding.

·         Program has only one exit point -  'GO BACK’ or ‘STOP RUN’.


·         All CALLs must be dynamic. This means the name of the program to be called must be held in working storage fields and the program called using this variable. For example,

         WC-ERROR-PROGRAM                    PIC X(6)          VALUE 'PGM001'.
         CALL WC-ERROR-PROGRAM USING WL-ERROR-VARIABLE

·          Use comments before CALL of any sub-program, sub-routine.
·         For arithmetic operations the following considerations apply
- No Display fields to be used as far as possible. 
- All fields have the same decimal alignment

·         Comparison must be done for fields satisfying the criteria
- Both fields have the same usage.
      - Alphanumeric fields are of equal length.
      - Numeric fields have the same decimal alignment.
      - Signed display fields must not be compared with alphanumeric fields

·         When 'MOVE'ing fields ensure as far as possible that :

 -  Both fields must have the same usage

-  In an alphanumeric MOVE, the receiving field length should equal the sending field length if possible, or else the receiving fields should be longer.

       -  There should be no truncation on a MOVE.

    -  COMP fields should be word aligned

       -  Numeric fields should have the same decimal alignment
       -  Conversion must be kept to a minimum

·         COMPUTE verb should be used in place of DIVIDE and MULTIPLY. For addition and subtraction, ADD, SUBTRACT may be used instead of COMPUTE verb.

·         Check for ZERO divisor before DIVISION.

·         The Use of Corresponding clauses should be avoided.

·         SET - Use SET < condition name > to TRUE rather than move specific values to variables.

·         SEARCH - Use Serial SEARCH when < 20 elements, else use binary search.

·         GO TO DEPENDING ON should not be used. Use EVALUATE instead

·         EXIT PROGRAM - not to be used. Instead GOBACK should be used

·         Use the CONTINUE statement and not the NEXT SENTENCE statement.

·         Do not use   ACCEPT to obtain data from a SYSIN DD * card

·         Avoid deliberate use of PERFORM for few statements. The number of instructions required to execute PERFORM may be more than that required to execute those statements.
  
 Error Handling:

Unexpected errors must be catered for within the program in a consistent manner. The use of Displays must be avoided as far as possible.


General coding principles:

The ALTER instruction must not be used as it makes the code unnecessarily complex.
It is recommended that index rather than subscripts are used when accessing tables.
It is recommended that the 'SET condition-name TO TRUE' statement be used for assigning values to condition names when using 88 level indicators.

Structure:

Full use should be made of the verbs and constructs available with COBOL II i.e. INITIALIZE, END-IF, END-PERFORM, EVALUATE. Only use INITIALIZE to set groups to zero or spaces and restrict its use to the INIT section if possible. Do not use it to set fields to other values as this is very inefficient.


Maintainability:

Code should be easy to understand and therefore easy to maintain. Complex logic that will save a small amount of coding should be avoided if it is difficult to follow.

Batch Output Files:

Programs writing output files should be opened with OUTPUT not EXTEND. The JCL displacement should reflect a file extension with DISP=MOD and DISP=OLD for files being overwritten.



User Controlled Abends:

Under certain conditions it may be required to terminate a program in a controlled manner. An Example of this could be when the integrity of a data file cannot be determined.

For DB2 programs the "User Abend" is the safest way to terminate a program to force a rollback of any work up to the last commit point.

The user abend is invoked by using code similar to the following:-

                           COPY ABEND. (In Working-storage section)

          Code
                           MOVE '1234' TO WS-ABEND-CODE.
                           CALL ' ZZZABEND' USING WS-ABEND-CODE.

The above code will cause the program to abend with a completion code of "U1234".
Note: Only values in the range 0-4095 can be used s user abend codes due to the picture clause used by module ZZZABEND.

An alternative method in DB2 programs is to issue a ROLLBACK, terminate the program with the RETURN-CODE set.  This will ensure any output files are retained.

To terminate a program without an ABEND (ie. there are no database updates to consider) a simpler method can be used. COBOL contains a reserved dataname called RETURN-CODE. A value can be moved to this dataname during any point within a program and the return code will be set on completion.

             eg.        MOVE 8 to RETURN-CODE.
         
Sub-programs should not issue abends or set the return code, instead they should pass status codes back to the calling program where action will be taken.

Saturday, January 1, 2011

Important DB2 SQL Codes


 SQL CODES                       DESCRIPTION


    000                  Sql Statement finished succesfully
   +100                  No rows satisfied the sql statement
   +117                  No of values being inserted is not equal to no. of                            columns in the table being inserted to
   +162                  Named table space is placed in check pending                                  status                                   
   +204                  Named Object is not defined to Db2
   +205                  Named column does not exist in the named table
   +206                  Named column does not exist in any table which is                             named in the sql statement
   +625                  Table defination marked incomplete because                                    primary Key index was dropped
   +802                  Data Exception error caused by data                                           overflow/divide Exception
   -007                  Sql Statement contains illegal character
   -029                  INTO clause is required
   -060                  Specified Data type has an invalid length/scale                               specefication
   -084                  Sql statement can’t be excuted because it is invalid                         for Dynamic sql/is an sql /ds statement
   -101                  Sql statement exceeds an established DB2 limit                                (Too many tables / Too many bytes in the statement)

Date/Time         


   -180                  Syntax for string representation of  Date/Time                                value is invalid
  -181                  String representation of Date/Time value is invalid
   -182                  Date/Time value in an arithmetic expression is                                invalid
   -183                  Result of arithmetic expression Returns a                                     Date/Time value that is not in the range of valid                             values

Cursors

 
  -501                   Cursor must be opened before attempting to fetch                              from it  or close it   
  -502                   Cursor can’t opened twise without first closing it
  -503                   Column can’t be updated because it was not specified in
                        the FOR UPDATE OFF clause of the cursor from it was       
                        fetched
  -504                   Cursor can’t be referenced because it defined to                              the program
  -507                   Cursor must be opened before attempting to                                    update/delete  WHERE CURRENT OF
  -508                   You can’t update or delete because referenced                  
                        cursor is not positioned in a data row
  -509                   You can’t upate from a different table than the one  
                        specified on the cursor referenced by WHERE                  
                        CURRENT OF clause


Referential Integrity

 
  -530                   Invalid foreign key was specified for specified                               constraint name
  -531                   Primary key value can’t be updated if foreign keys                            currently exist that reference that value
  -532                   Deletion violates the named referential constraint
  -533                   Multiple row insert is invalid; Attempting to insert                          multiple rows into a self referencing table
  -534                   Update statement changing primary key column               
                        can’t be used to update more than one row at a time
  -535                   WHERE CURRENT OF can’t be specified when deleting from a
                        self referencing table or updating primary key column
  -536                   Delete statement is invalid due to referential                                constraints existing for the specified table
  -537                   Single column can’t  appear more than once in        
                        foreign/primary key clause specification
  -538                   Foreign key is invalid. Because it does not conform  to
                        the definition of referenced table primary key
  -539                   Foreign key can’t be defined because the             
                        referenced table does not have primary key
  -540                   Table definition is incomplete until unique index is  
                        created for the primary key
  -551                   User is attempting to perform an operation on the                             specified object for which user is not authorised or                         Table does not exist
  -601                   An attempt was made to create an object that             
                        already exists   
  -602                   Too many columns were specified in CREATE INDEX
                        statement
  -603                   Unique index cannot be created because duplicates                             were found
  -607                   INSERT,UPDATE,DELETE can’t be issued as written against
                        the DB2 catalogue tables
  -612                   Duplicate column names are permitted in single table
  -803                   Row can’t be inserted because it would violate the                            constraints of the unique index
  -818                   Time Stamp Mismatch
  -904                   Specified resource is unavailable
  -911                   Current unit of work has  been Rolled back
  -913                   Execution is unsuccessful due to                     
                        DEADLOCK/TIME OUT
  -922                   Connection authorisation failure. Attempt made to    
                        access DB2 from TSO, CICS,IMS and appropriate attachment
                        facility is inactive