Top Banner

of 39

Bilal Ahmed Shaik-COBOL Programming STD

Apr 06, 2018

Download

Documents

Neo Dragon
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    1/39

    COBOL Programming Standards

    Introduction

    Now a days it is common practice to use a particular method of Structured Design beforeproducing the code that will fulfil a particular function. No matter what Design Methodology isused, the whole object of using structured programming techniques is lost if the actual codeproduced is badly written. Not only must the code fulfil its desired function, and perform itefficiently, it must also be maintainable by all those programmers who follow in your wake. Inthe life of any program more time is spent on maintenance and enhancement than was ever spenton the original implementation.

    COBOL is a flexible, free-format language that has very few internal constraints. It does notenforce any particular structural method, instead it allows the individual to adopt whatever

    structure their particular level of mentality can imagine.

    The author of this document has over a decade's worth of experience in writing COBOLprograms, and has encountered many different standards, each with its own set of strong as wellas weak points. Some are too rigid and unnecessarily restrictive, while others are too flexible andopen to misinterpretation. Those which do not encourage or promote efficient, readable andmaintainable code have been discarded, and the remainder have been reviewed and modified inthe light of experience, common sense and logic.

    In those installations where programmers are allowed to adopt whatever style takes their fancy itis sometimes necessary to be familiar with an individual's style before it is possible to work on

    one of their programs. If a program has been worked on by several different programmers themixture in styles can sometimes be very confusing. However, in those installations where properstandards and a common style of coding have been adopted it should be possible for anyprogrammer to work on any program without knowing the identity of the previous authors.

    This is known as "ego-less programming", and is something which this document is intended toencourage and promote. These standards are meant to show how code can be written in such away as to be more readable, easier to understand and therefore more maintainable. A well-written program should read like a piece of prose, not a bunch of gobbledygook.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    2/39

    Source Code Documentation

    I am a great believer in having my source code liberally sprinkled with documentation in theform of comment lines (those with an asterisk in column seven). Any program which does not

    contain comments is immediately suspect - it may actually work, but how easy is it to maintainor modify? There may be separate written documentation, but there re distinct advantages inproducing self- documenting code:

    Separate documentation (if it exists at all!) has a habit of becoming `misplaced', whereasthe program's source code is always available, either on magnetic disc or tape, or in afiled listing.

    Separate documentation has a habit of not being updated to reflect changes made to thesource code. All too often documentation updates are left till last, or not done at all.

    It is sometimes quite difficult to identify which piece of code is responsible forperforming a particular function outlined in the documentation.

    How can self-documenting code be produced?

    Meaningful data names in the data division. Meaningful section/paragraph names in the procedure division. Plenty of comment lines to explain to the reader what is happening, and why.

    It helps if all comments are in lower-case, to differentiate from actual commands which shouldalways be in upper-case. Leave only one space between the asterisk in column seven and thestart of the comment - more spaces are laborious to enter in the first place, and certainly don'tmake the comments easier to read.

    There is one acid test to prove that your program is adequately documented - can you reconstructall the written documentation from your source code? If the answer is NO, then you have failed.There are some products available nowadays which will do the job for you - they read yoursource code and produce all the separate documentation that you require. It should be obvious,therefore, that products such as these cannot extract information which is not there to begin with.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    3/39

    Program Identification

    The IDENTIFICATION DIVISION of any COBOL program must contain at least the programname. This is also the best place in which to record other useful information which will serve as

    an introduction to the program as a whole. Such `useful information' can be summarised asfollows:

    1. PROGRAM NAME - this should follow the company's naming conventions, it should beunique for each program, and should also be linked with the name of the source file.

    2. AUTHOR - so we will know who to blame when things go wrong!3. DATE-WRITTEN - this gives us the age of the original version.4. DATE-COMPILED - this is automatically inserted by the COBOL compiler, and shows

    the age of the current version of this program.5. Program function - what is its purpose? Is it a stand-alone program, or part of a suite of

    programs? When is it run?

    6.

    Database access - what databases are used, and in what modes?7. Dataset access - what datasets are used, and how are they accessed (read, write, update ordelete)?

    8. Non-database file access (MPE, KSAM) - identify which files are accessed, and how.9. Print files - what reports are produced, and what special stationery is required?10.VPLUS processing - what is the name of the forms file, and what are the names of the

    individual forms?11.Subroutine usage - identify any subroutines called by this program, giving the name and a

    brief description.12.Amendment history - each time a program is changed you should insert a note giving the

    amendment date, a brief description of the amendment, plus your name.

    Items (a) (b) (c) and (d) can be specified using the standard COBOL Identification Divisionstatements. The remainder should be included as comment lines.

    Even though all of the above information can be obtained by close examination of the code, itsaves a lot of time (and time is money!) by having it laid out at the start of each program listing.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    4/39

    Program Data

    * Record Definitions

    The DATA DIVISION of any program is a mixture of individual record names subdivided intonumerous item names, which in turn can be subdivided into various sub-items.

    Items which are not subdivided are known as elementary items. Items which are subdivided areknown as group items, with the record name being equivalent to the highest level of group item.

    In COBOL all data items are defined in the following manner:

    where

    is a two-digit number which starts at 01 for record names and ascends up to 49for all data items which are to be considered part of that record definition.

    is the name by which that particular data area can be referenced from within theprogram.

    describes the format of that particular data-name (alphabetic, numeric, etc.).

    The picture clause is required only for elementary items - record names and group items assume

    a picture of PIC X(n) where `n' is the combined length of all the subordinate items within thatgroup definition.

    It is therefore possible to construct a record definition as follows:

    01 RECORD-NAME.02 DATA-NAME-1-ALPHA PIC X(2).02 DATA-NAME-2.03 DATA-NAME-3-NUMERIC PIC 99.03 DATA-NAME-4.04 DATA-NAME-5-ALPHA PIC X(2).04 DATA-NAME-6-NUMERIC PIC 9(5).02 DATA-NAME-7-ALPHA PIC X(6).

    This layout, however, is totally unacceptable in a structured program because it is not easy todetermine which elementary items go with which group items. It would be easier to read if somesort of indentation was used to differentiate between the various level numbers, and if there wassome space between the data name and the picture clause.

    This example shows the effect of indenting the data names but not the level numbers:-

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    5/39

    01 RECORD-NAME.05 DATA-NAME-1-ALPHA PIC X(2).05 DATA-NAME-2.10 DATA-NAME-3-NUMERIC PIC 99.10 DATA-NAME-4.15 DATA-NAME-5-ALPHA PIC X(2).15 DATA-NAME-6-NUMERIC PIC 9(5).05 DATA-NAME-7-ALPHA PIC X(6).

    This example shows the effect of indenting the level numbers, but not the data names:-

    01 RECORD-NAME.05 DATA-NAME-1-ALPHA PIC X(2).05 DATA-NAME-2.

    10 DATA-NAME-3-NUMERIC PIC 99.10 DATA-NAME-4.

    15 DATA-NAME-5-ALPHA PIC X(2).15 DATA-NAME-6-NUMERIC PIC 9(5).

    05 DATA-NAME-7-ALPHA PIC X(6).

    The following example is the best because it indents both the level number and its associateddataname. Note that each different level number is aligned in a separate column, making it easierto spot any mistakes.

    01 RECORD-NAME.05 DATA-NAME-1-ALPHA PIC X(2).05 DATA-NAME-2.

    10 DATA-NAME-3-NUMERIC PIC 99.10 DATA-NAME-4.

    15 DATA-NAME-5-ALPHA PIC X(2).15 DATA-NAME-6-NUMERIC PIC 9(5).

    05 DATA-NAME-7-ALPHA PIC X(6).

    Note that all the picture clauses are aligned in the same place, usually at column 40. Where adata name flows into this column the most common practice is to put the picture clause on thefollowing line, thus keeping the alignment consistent, eg:

    05 DATA-NAME-2.10 DATA-NAME-2A.

    15 THIS-IS-ANOTHER-LONG-DATANAMEPIC X(2).

    15 THIS-IS-YET-ANOTHER-LONG-DATANAMEPIC 9(5).

    The guidelines for record layouts can be summarised as follows:-

    1. Level numbers should be incremented by more than one in order to leave room for futureadditions of group items without having to renumber a whole section (increments of 01,03, 05, etc are acceptable, but 01, 05, 10, etc is even better).

    2. Level 01 should start in column 8, and all following numbers should be indented so thateach different level number is aligned in a different column.

    3. The indentation between one level number and the next should be 4 columns.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    6/39

    4. There should be 2 spaces between a level number and its associated data name.

    The effect of items (c) and (d) is that the data names for one level are aligned in the same columnas the level numbers for the next level. This may seem irrelevant, but I think that it looks better.When using the QEDIT text editor in full-screen mode it is possible to define the tab stops at

    columns 8,12,16,20,24,28 etc, therefore the same tab settings can be used for both level numbersand data names.

    * Print Line Definitions

    Now for some advice on how to describe headings for batch reports. Here are three ways ofdescribing the same print line:

    Example 1:

    01 HEADING PIC X(132) VALUE

    "ITEM DESCRIPTION QUANTITY UNIT PRIC- "E TOTAL PRICE VAT".

    Example 2:

    01 HEADING.05 FILLER PIC X(4) VALUE

    "ITEM".05 FILLER PIC X(6) VALUE

    SPACES.05 FILLER PIC X(11) VALUE

    "DESCRIPTION".05 FILLER PIC X(19) VALUE

    SPACES.05 FILLER PIC X(8) VALUE

    "QUANTITY".05 FILLER PIC X(2) VALUE

    SPACES.05 FILLER PIC X(10) VALUE

    "UNIT PRICE".05 FILLER PIC X(2) VALUE

    SPACES.05 FILLER PIC X(11) VALUE

    "TOTAL PRICE".05 FILLER PIC X(1) VALUE

    SPACE.

    05 FILLER PIC X(3) VALUE"VAT".

    Example 3:

    01 HEADING.05 FILLER PIC X(10) VALUE "ITEM".05 FILLER PIC X(30) VALUE "DESCRIPTION".05 FILLER PIC X(10) VALUE "QUANTITY".

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    7/39

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    8/39

    LIST "ACC-"LIST "MOVE ACC-"LIST "TO ACC-"

    * Item Names

    COBOL allows data names to be up to 30 characters in length. However, most programs whichrun on the HP3000 tend to have some sort of access to either IMAGE databases or VPLUSscreens, where the length of data items is limited to 16 and 15 characters respectively.

    Item names should convey some sort of description as to their content, and in order not to exceedthis 15-character limit it is sometimes necessary to use abbreviated terms. Whatever abbreviationis chosen it is important that the same one is used throughout the system. For example, thefollowing combination of item names within the same system is very sloppy:-

    LINE-NUMBERACCOUNT-NBR

    INVOICE-NUMDOC-NO

    Where the same item appears in more than one place within the system (eg: in an IMAGEdataset, or a VPLUS screen) it is a very good idea to keep to the same spelling.

    Where the item is subsequently defined within a program's data division (eg: in the datasetbuffer, the screen buffer, or a print buffer) it is also a very good idea to keep to the same spelling.The only difference should be in the prefix, which acts as an identifier for the particular buffer.

    The only exception to this guideline is where an item occurs more than once on a VPLUS screen.

    As the OCCURS clause does not exist within FORMSPEC it is necessary to give eachoccurrence of the item a unique name. This is done by appending a 2 digit sequence number(starting at "01") to each occurrence of that item name. This suffix can be dropped within theCOBOL definition as the OCCURS clause can be used instead. There should then be a directrelationship between the hard-coded number in the forms file and the occurrence number withinthe COBOL array, as demonstrated in the following example:

    VPLUS: ITEM-NAME01,ITEM-NAME02,,,,,,,ITEM-NAME09,ITEM-NAME10

    COBOL: ITEM-NAME PIC X(?) OCCURS 10.

    If it becomes necessary within your program to identify one of these field names (eg: to pass to

    the SCVSETERROR routine after a failure in some validation) it can be constructed as ITEM-

    NAMEnn where nn is the occurrence number.

    * Working Storage Definitions

    Data definitions within a program's WORKING-STORAGE section can be a mixture of datasetbuffers, screen buffers, and general work areas.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    9/39

    Each item name should be prefixed by a different mnemonic depending on the record definitionin which it appears. IMAGE dataset buffers and VPLUS screen buffers should have beenallocated their own unique mnemonics, but what of the general work areas?

    Some standards say that all WORKING-STORAGE definitions must be prefixed with the letter

    `W', but in very large sections it can be a long-winded process to find an individual definition.

    Other standards say that the prefix should be two characters in order to denote the general usage,as in the following:

    WA- accumulatorsWC- constantsWI- indicators/flags/switchesWM- modifiers/subscriptsWT- tables/arrays

    However, I much prefer to see groupings of items which are related logically, rather than

    functionally, as in the following:

    01 T01-COMPONENT-TABLE.05 T01-MAX PIC 99 VALUE 20. 05 T01-CURR PIC S9(4) COMP. 05 T01-LAST PIC S9(4) COMP. 05 T01-TABLE-ENTRY OCCURS 20.

    10 T01-CODE PIC X(6).10 T01-DESCRIPTION PIC X(30).10 T01-VALUE PIC S9(7)V99 COMP.

    05 T01-TOTAL-VALUE PIC S9(7)V99 COMP.

    Even though each item has a different function, they are all logically related, as they are

    concerned with that particular table and no other. It also makes it easier to search through thesource code to find any reference to this data area simply by specifying a search string of "T01".

    The following definition is also acceptable, but it has a distinct advantage when using theCOBOL'85 compiler, which allows a group of data items to be reset to blanks or spaces with asingle statement.

    01 T01-MAX PIC S9(4) COMP VALUE 20.

    01 T01-COMPONENT-TABLE.05 T01-CURR PIC S9(4) COMP.05 T01-LAST PIC S9(4) COMP.

    05 T01-TABLE-ENTRY OCCURS 20.10 T01-CODE PIC X(6).10 T01-DESCRIPTION PIC X(30).10 T01-VALUE PIC S9(7)V99 COMP.

    05 T01-TOTAL-VALUE PIC S9(7)V99 COMP.

    Although the item T01-MAX has been taken out of the original layout and changed from an 05

    level to an 01 level it has still retained the T01- prefix to show that it is still related logically.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    10/39

    Thus the statement INITIALIZE T01-COMPONENT-TABLE will correctly reset to zeros/spaces thevalues of all T01- items except for T01-MAX, which must remain at 20.

    As a general rule, then, the WORKING-STORAGE section should be laid out in logical groupswith prefixes as follows:

    Tnn- tables/arraysWnn- other

    These should be defined in their proper sequence so that it is easy to locate any individual dataitem when searching through a program listing. Any copy library members for dataset/filebuffers should be correctly sequenced by their respective prefix values. This avoids the need toproduce a cross-reference listing which incurs a considerable overhead, both in compilation timeand printing time.

    * Subscripts and Indices

    Some people like to define global subscripts/indices in the form SUB1, SUB2....SUBn (orINDX1, INDX2,,,INDXn). This is bad practice because there is no logical relationship with anyparticular table/array, and the names do not convey any sort of meaning.

    It can take a long time to debug a program if the same subscript is accidentally used to referencetwo different tables at the same time, or two different subscripts are accidentally used toreference the same table at the same time.

    This is not a problem if the name of the subscript/index item is constructed in the format

    - where:-

    indicates the table to which it has been associated,

    indicates how this particular item is used.

    As can be seen in the previous section the subscript item used to access T01-TABLE-ENTRY is

    named T01-CURR. This cannot easily be confused with T01-MAX, which is used to indicate the

    maximum number of entries the table may contain, and T01-LAST which indicates the actualnumber of entries in the table at present.

    * Condition NamesCondition names are used to show an expected range of values for a particular data item. Once acondition-name has been defined, that particular name can be used instead of testing the dataitem for a specific value (or range of values). Take the following definition in a program'sworking-storage section:

    05 IMAGE-STATUS PIC S9(4) COMP.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    11/39

    88 IMAGE-OK VALUE ZERO.88 IMAGE-ERROR VALUE -9999 THRU -1,

    +1 THRU +9999.88 IMAGE-BEG-OF-FILE VALUE 10 12.88 IMAGE-END-OF-FILE VALUE 11 13.88 IMAGE-BEG-OF-CHAIN VALUE 14.88 IMAGE-END-OF-CHAIN VALUE 15.88 IMAGE-DSET-FULL VALUE 16.88 IMAGE-NO-ENTRY VALUE 17.88 IMAGE-LOCK-FAILURE VALUE 20 THRU 25

    The contents of IMAGE-STATUS can be determined in two ways:

    IF IMAGE-STATUS = ZERO becomes IF IMAGE-OK

    IF IMAGE-STATUS NOT = ZERObecomesor

    IF NOT IMAGE-OKIF IMAGE-ERROR

    With COBOL'85 it is now possible to set a condition by referring to the name instead of theactual value, eg:

    MOVE 0 TO IMAGE-STATUS

    is the same as

    SET IMAGE-OK TO TRUE

    There are only 2 simple guidelines to follow when defining condition-names:

    1. Use a meaningful description for each condition;2. Use a prefix which links the condition-name with the particular data item for which it is

    defined. This makes it easier to locate the reference in the working-storage section, and in

    most cases should make the condition being tested completely obvious (eg. IMAGE-OK,KSAM-OK or VPLUS-OK).

    * Flags/Indicators/Switches

    As a general rule any program that uses its own set of switches or indicators is badly written.Most conditions can be handled by data areas that have already been defined (eg: the status areasfor VPLUS, IMAGE and KSAM).

    If it does become necessary to use a separate indicator then please follow these simpleguidelines:-

    1. Use meaningful data names (not SW1, SW2, SW3, etc).2. Do not use an indicator for more than one purpose.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    12/39

    Here are a few more observations regarding flags and switches:-

    In an online program it is not necessary to define a flag which shows the success orfailure of a validation routine as the item VIEW-NUMERRS is already available for thispurpose. This has the condition names VEDIT-ERRORS and NO-VEDIT-ERRORS.

    Do not use a flag to test for a condition if that condition can be obtained from othermeans, as in the following example:

    IF LINE-COUNT > LINE-MAX (ie: the current page is full) MOVE 1 TO NEW-PAGE-REQUIRED. ........ IF NEW-PAGE-REQUIRED = 1 PERFORM XA-START-NEW-PAGE.

    can be replaced by:

    IF LINE-COUNT > LINE-MAXPERFORM XA-START-NEW-PAGE.

    When reading a serial file it is not necessary to define a flag to show when end-of-file hasbeen encountered, as the same result can be achieved by setting the file's record area toHIGH-VALUES, as in the following example:-

    MOVE LOW-VALUES TO ABC-REC. PERFORM UNTIL ABC-REC = HIGH-VALUES READ ABC AT END MOVE HIGH-VALUES TO ABC-REC NOT AT END PERFORM CA-PROCESS-ABC-REC

    END-READ END-PERFORM.

    Program Code

    * Introduction

    The PROCEDURE DIVISION in any COBOL program contains one or more SECTIONS. EachSECTION contains one or more PARAGRAPHS; each PARAGRAPH contains one or moreSENTENCES; and each SENTENCE contains one or more STATEMENTS.

    A SECTION is identified by having a unique name starting in column 8 followed by thereserved-word `SECTION'. It ends with the start of the next section, and NOT when an`EXIT' statement is encountered.

    A PARAGRAPH is identified by having a unique name starting in column 8 (the namemust be unique within a section, but may be duplicated in other sections). It ends with thestart of the next paragraph. There need be no relationship between a SECTION name andits associated PARAGRAPH name(s).

    http://www.tonymarston.net/cobol/cobolstandards.html#exithttp://www.tonymarston.net/cobol/cobolstandards.html#exithttp://www.tonymarston.net/cobol/cobolstandards.html#exithttp://www.tonymarston.net/cobol/cobolstandards.html#exit
  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    13/39

    A SENTENCE starts in column 12, can continue over several lines, and is terminated by

    a full stop. A STATEMENT contains a single COBOL verb, a subject name, and an optional object

    name (eg: MOVE A TO B, ADD C TO D, PERFORM E).

    Control can be passed from one point in a program to another by means of the followingstatements:

    PERFORM .PERFORM .PERFORM THRU .GO TO .

    These guidelines are extremely flexible, but without additional guidelines the resulting code canbe as manageable as a plate of limp spaghetti - please read on for your elucidation andedification.

    * Program Structure

    ** Module Hierarchy

    It is common practice in modern programming to split the code into logical sections or modules.Each section/module performs a particular function, and is invoked by the statement:

    PERFORM .

    Each section/module can, in its turn, invoke other sections to perform lower level functions. Thisproduces a modular hierarchy or structure, hence the term `structured programming'. It is usualto plan the structure of a program at the design stage before writing any code, in order to producea structure similar to that shown in Figure 1:

    Figure 1 - Module Hierarchy

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    14/39

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    15/39

    Where the initial design produces a box which is a combination of ITERATION/SEQUENCE orITERATION/SELECTION most methodologies insist that the structure be preserved by splittingthe two and performing the ITERATION part at a lower level.

    ** Module Naming

    It is common practice to give each module some sort of mnemonic to denote its position in themodule hierarchy, both horizontal and vertical. In the example given in section 5.2.1 eachmodule is named from left-to-right and top-to-bottom, but there is no relationship between themnemonics of modules which have some sort of logical association.

    There are two other methods of arriving at mnemonic names, and these are discussed below:

    1. POSITIONAL - the mnemonic has two alphabetic characters, the first denotes theLEVEL (top to bottom) while the second denotes the SEQUENCE (left to right). Usingthe same hierarchy as shown inFigure 1this is demonstrated in Figure 2:

    Figure 2 - Module Hierarchy (positional)

    2. FUNCTIONAL - the first character denotes the sequence of the top-level function, whilethe second and subsequent characters denote a combination of level-within-function andsequence-within-level. This is demonstrated in Figure 3:

    Figure 3 - Module Hierarchy (functional)

    http://www.tonymarston.net/cobol/cobolstandards.html#figure1http://www.tonymarston.net/cobol/cobolstandards.html#figure1http://www.tonymarston.net/cobol/cobolstandards.html#figure1http://www.tonymarston.net/cobol/cobolstandards.html#figure1
  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    16/39

    Now let us discuss the relative merits of both methods.

    It is common sense when coding the procedure division to place the sections in mnemonicsequence - this makes it easier to find your way through the listing. Inmethod (b)this means thateach leg within the program structure forms a contiguous block, whereas inmethod (a)the samesections are spread out all over the place. This is shown more clearly in Figure 4:

    Figure 4 - Positional vs. Functional naming

    Positional Functional

    http://www.tonymarston.net/cobol/cobolstandards.html#functionalhttp://www.tonymarston.net/cobol/cobolstandards.html#functionalhttp://www.tonymarston.net/cobol/cobolstandards.html#functionalhttp://www.tonymarston.net/cobol/cobolstandards.html#positionalhttp://www.tonymarston.net/cobol/cobolstandards.html#positionalhttp://www.tonymarston.net/cobol/cobolstandards.html#positionalhttp://www.tonymarston.net/cobol/cobolstandards.html#positionalhttp://www.tonymarston.net/cobol/cobolstandards.html#functional
  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    17/39

    Using method (b) it is possible to increase or decrease the number of sections in a particularprocessing leg without having to rename any other sections in order to maintain the namingsequence. See how easy it is in method (b) to split section "DA" into "DAA" and "DAB", thentry and make the corresponding change in method (a).

    Another advantage ofmethod (b) is that when a program becomes too large for a single unit andneeds to be segmented or split into subprograms it is easy to identify which modules are logicallyrelated and therefore eligible for separation. Compare those modules marked above in method(b) with the corresponding modules from method (a).

    In a large, complex program with many modules method (b) may produce mnemonics which arelarge and cumbersome - how can this be overcome? Common sense to the rescue - identify asub-function with a large number of modules and start naming them using a different letter fromthe alphabet, as shown in Figure 5:

    Figure 5 - Restarting the prefix character

    For a sorted report which has a large number of control breaks it is acceptable to introduce anumber into the mnemonic, and to increment this number for each lower level instead ofincreasing the length of the mnemonic by adding another character. This would produce astructure chart something like the one in Figure 6:

    Figure 6 - Numerical Sequencing

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    18/39

    With this method all the processing for a particular sort level would be held in contiguoussections as the sequence would be as follows:-

    R, R1, R1A, R1B, R2, R2A, R2B, R3, R3A, R3B, R4, R4A, R4B, R5

    Some standards have a rule that if a section has more than one parent (ie: can be called frommore than one section at a higher level) then it should be allocated a prefix which represents ageneral-purpose routine, usually at the bottom end of the alphabet (eg: X, Y or Z). This is fine ifit is a small section with limited processing, but what if it is just the start of a significant piece ofcoding?

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    19/39

    Take the following example - A database is comprised of customers who are grouped intocountries, which in turn are grouped into regions. A program processes the details for customersat the end of each month, but the selection criteria can be one of the following:

    1. A single customer,2.

    A single country, for all customers within that country,3. A single region, for all countries within that region,

    4. All regions (ie: all customers).This would produce a structure chart something like the one shown in Figure 7:

    Figure 7 - A Module with multiple parents

    Notice that the selection processing is handled by modules which have the "C" prefix, while theactual customer processing (regardless of the selection method) has a separate prefix. This makestracing your way through the source code a lot easier, which is more important than conformingto inflexible rules with their artificial restraints.

    * Sections

    The guidelines for sections can be summarised as follows:-

    1. Each section should start on a new page.2. Each section name should be prefixed by a unique mnemonic containing one or more

    alphanumeric characters to denote that section's position in the program's hierarchy ofsections.

    3. Each section name should be a short but meaningful description of the function of thatsection (eg: CA-SELECT-COMPONENT, DEA-UPDATE-COMPONENT).

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    20/39

    4. The entire PROCEDURE DIVISION should be arranged in mnemonic sequence so that

    individual sections can be found more easily.

    5. Control should be passed from one section to another by means of the PERFORM statement, and not the GO TO statement, nor the PERFORM

    THRU statement.

    6. Each section must have a single entry point (the first paragraph) and a single exit point(the last paragraph).7. Each section should be limited to perform one basic function, whether it be HIGH-

    LEVEL (eg: deciding which selection of lower level procedures to perform) or LOW-LEVEL (eg: reading from or adding to a data file).

    8. Each section should be short enough to be contained on a single page of listing paper.Anything longer than this should be broken down into a series of sub-sections, each withits own separate function.

    9. Between the section-name and first paragraph-name there should be a brief commentas to the overall function of that particular section (leave more detailed comments untilyou get to the actual code). It helps to make this description more distinctive if it is

    enclosed by a line of asterisks immediately before and after, producing a `box' effect.

    * Paragraphs

    The guidelines for paragraphs can be summarised as follows:-

    1. Each paragraph name should be a short but meaningful description of the function of thatparagraph.

    2. Each paragraph name should be prefixed by the mnemonic that has been previouslyassigned to that section, plus an ascending sequence number, (eg: BA-10-READ-NEXT, BA-20-UPDATE).

    3. This sequence number should be in increments of ten, starting at ten for each newsection. This leaves adequate room for future additions without having to renumberexisting paragraphs.

    4. Two digits are adequate for the sequence number - if any more are required it means thatyou have already broken the guideline regarding the size of your section.

    5. The last paragraph should contain nothing but theEXITstatement, and need not have asequence number (eg: BA-99-EXIT or BA-EXIT).

    6. If you need to pass control to another point within the same section use the GO TO statement. Do NOT use the PERFORM statement.

    7. If you need to pass control to another section use the PERFORM statement. Do NOT use the GO TO statement on anything other than a paragraph-name

    within the current section.8. If you feel it necessary to insert a comment (or two) about the paragraph, please put it

    AFTER the paragraph name and BEFORE the first line of code.

    * Sentences and Statements

    The guidelines for sentences and statements can be summarised as follows:-

    http://www.tonymarston.net/cobol/cobolstandards.html#exithttp://www.tonymarston.net/cobol/cobolstandards.html#exithttp://www.tonymarston.net/cobol/cobolstandards.html#exithttp://www.tonymarston.net/cobol/cobolstandards.html#exit
  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    21/39

    1. Each sentence should start in column 12.2. Each statement within a sentence (if there is more than one) should start on a separate

    line. This means that statements can be added or deleted quite easily, without having tochange other lines unnecessarily.

    3. If a statement is too long to fit on one line DO NOT split a data-name across two lines -instead move the whole name (along with the TO, FROM, BY or GIVING portion of the verb)onto the next line, indenting by four character positions.

    4. Do not use weird spacing between each word - one is enough! There is only oneexception to this guideline that I find acceptable, and that is when there is a group ofMOVE ..... TO ..... statements. In this case it makes the code more readable if all the

    TO portions are aligned under a common column, as in the following example:5. MOVE "AA" TO ACC-ACCOUNT-TYPE.6. MOVE ABC-GROUP TO ACC-GROUP.7. MOVE ABC-CLASSIFICATION TO ACC-CLASSIFICATION.8. MOVE ABC-NAME TO ACC-NAME.

    guidelines (c) and (d) come in handy when searching a source file for a particular

    references to a data-name, as with:

    LIST "MOVE ABC-GROUP"LIST "TO ACC-GROUP"

    This is not so easy to do if the data-name is split in two, or if more than one space is usedbetween words.

    9. Do not put a space line between individual statements. It is permissible, however, to havea space line between groups of statements in order to show a logical separation.

    10.Even though it should be obvious WHAT a piece of code does, it may not be obviousWHY it does it, or WHY it is necessary to do it at that particular point in the program. Toaid the maintenance programmer some sort of comment may be worth its weight in gold.Don't worry if the comment stretches over several lines - a single- line comment isworthless if it is incomplete.

    * Conditional Processing

    This is where a lot of uneducated programmers come unstuck! Even though COBOL allows thefollowing:

    IF {THEN} ELSE {END-IF}.

    There are some basic guidelines which can be applied in order to make the code more readableand easier to maintain. These are:

    1. Each portion (condition, ELSE, statement-1, statement-2, END-IF) should be on a separateline. This allows for future additions or deletions without having to modify more linesthan is necessary.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    22/39

    2. The word ELSE should be aligned in exactly the same column as the IF to which it is

    associated. This makes the association more obvious in the listing, especially with

    multiple or nested IFs.

    3. COBOL'85 allows each condition to be terminated with an END-IF. Its use should beencouraged as it makes it absolutely clear where each condition is supposed to end, thus

    avoiding the possibility of confusion and mistakes. Like the ELSE, the END-IF should bealigned in exactly the same column as IF with which it is associated.

    4. Statement-1 and statement-2 should be indented, usually by four character positions. Thisallows the IF, ELSE and END-IF to be more distinctive in the listing.

    This now gives us the following construction:

    IF

    ELSE

    END-IF.

    Here are some extra guidelines for nested IFs:

    5. For each level of nested IF indent all associated lines by four characters. This gives thefollowing:

    6. IF 7. IF 8. 9. ELSE10. 11. END-IF12. ELSE13. 14. END-IF.15.Don't ever use more than three levels of nested IF - they are extremely difficult to debug

    and maintain.

    16.Remember that each ELSE is paired with the IF that immediately precedes it in the code,not necessarily the one under which it is aligned. Take the following example:

    17. IF 18. IF 19. 20. ELSE21. .

    According to the indentation is supposed to be executed if is false, but COBOL follows its own rules and executes if is true and is false. This type of error is more avoidable

    if the END-IF is used, as in the following example:

    IF IF

    or...

    IF IF

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    23/39

    END-IFELSE

    END-IF.

    ELSE

    END-IFEND-IF.

    22.In the case where an ELSE is immediately followed by an IF without any interveningstatements (ie: where only one out of a series of conditions will be TRUE) it is notnecessary to indent at each new IF otherwise you will quickly fall off the page. Considerthe following example:

    IF X-VALUE = 1

    ELSEIF X-VALUE = 2

    ELSEIF X-VALUE = 3

    ELSEIF X-VALUE = 4

    ELSEIF X-VALUE = 5

    etc.

    IF X-VALUE = 1

    ELSEIF X-VALUE = 2

    ELSE

    IF X-VALUE = 3

    ELSEIF X-VALUE = 4

    ELSE

    IF X-VALUE = 5

    etc.

    With the arrival of COBOL'85 this should be written as follows:

    EVALUATE X-VALUEWHEN 1

    WHEN 2 WHEN 3 WHEN 4 WHEN 5 WHEN OTHER .....

    END-EVALUATE.

    Here are even more guidelines for complex conditions:

    23.Enclose each individual condition in parentheses.24.If several conditions combine to form a group condition, (ie. all conditions have to be

    true in order to make the group condition true) then enclose the whole group in

    parentheses as well.25.By having each condition on a separate line, and by careful alignment of ANDs and ORs,

    it is possible to make absolutely clear that conditions are linked or are alternatives.

    These guidelines should produce something like this:

    IF ((A = 1 OR 2 OR 3)AND

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    24/39

    (B NOT = 4))

    OR ((C = "A" OR "Z")OR

    (D < E))

    ENDIF.

    This example, however, is rapidly approaching the stage at which it becomes toounwieldy to be maintainable. Don't be afraid to split a complex condition into its

    component parts, even if it involves the use of the GO TO statement. Don't try to provehow clever you can be - keep it simple and straightforward.

    * Hints, Notes and Warnings

    ** PERFORM

    Even though COBOL allows the PERFORM command to be used on paragraphs as well as

    sections, its use should be limited to sections only. If necessary make the offending paragraphinto a self-contained section, or an in-line PERFORM (if it is small enough). This guideline then

    avoids the possibility that someone may split the paragraph in two, thereby causing the PERFORMto terminate at the new paragraph name.

    Please note that if the word SECTION is missed out on a section name it will be treated as aparagraph. As there is usually nothing but comments between the section name and the next

    paragraph it means that no code will actually be executed by that PERFORM statement.

    Unfortunately the code WILL be included in the PERFORM of the preceding section. This usuallycauses lots of confusion.

    ** PERFORM ... THROUGH ...

    Avoid the use ofPERFORM THROUGH . It is good practice toname each procedure (section) explicitly - this makes it easier to search a source file for all

    occurrences ofPERFORM , and also avoids the possibility that someone may adda new section between existing sections without realising that it now falls within the bounds of

    the PERFORM THROUGH statement. A program can produce some very peculiar results ifa section is `accidentally' performed out of sequence, and is not easy to debug.

    ** The EXIT statement

    The EXIT verb in COBOL does not produce an EXIT instruction in the object program - it isignored, but is maintained for documentation purposes only. Whenever a section is PERFORMedCOBOL will generate its own (hidden) EXIT instruction when the next section-name is

    encountered. If a section-name in your source file has the word SECTION missing, COBOL willtreat it as a continuation of the preceding section - this can cause some very peculiar results(refer to PERFORM ).

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    25/39

    ** The GO TO statement

    Do not use the GO TO verb to transfer control to a point which is outside the current section asany implied EXIT points will be ignored. This means that the program will go where it thinks itshould go, which is probably NOT where it is supposed to go.

    ** The ALTER statement

    DO NOT USE THE ALTER STATEMENT! If you need to change the processing sequence due to

    a certain condition, then use an alternative set ofPERFORM or GO TO statements - trying to debuga program where the instruction as it appears in the listing may not be the actual instructionencountered by the program at run time is a very frustrating experience. If it makes themaintenance programmer's job more difficult thenDO NOT USE IT!

    ** MOVE CORRESPONDING

    This may seem to be an economical way of writing source code as this single statement willrepresent several actual MOVE's. However, in the event of an error caused by an illegal ASCIIdigit (or similar) the diagnostic trace will not be able to identify which elementary item withinthe group of items actually generated the fault, which means that it will take longer to identifyand solve the problem.

    ** The COMPUTE statement

    The COMPUTE verb should be used only for complex arithmetic operations, and not for simple

    additions or subtractions. For example, use ADD 1 TO VALUE instead ofCOMPUTE VALUE =VALUE + 1 as it is more efficient in machine resources.

    The data items within a COMPUTE statement should, if possible, all have the same data type. If

    there is a mixture ofCOMP, COMP-3 and DISPLAY fields they will be converted (for the duration of

    the COMPUTE operation) to a common type before the calculation can take place.

    Be aware that the number of decimal places used in evaluating an arithmetic expression isdetermined by the maximum number of decimal places within the expression. This hasimplications when doing any divisions, especially when calculating percentages which have animplied division by 100. For example, to apply a rate of 17.25% you have the choice of either:

    1. Including the division by 100 within the calculation by specifying * 17.25 / 100, or2. Performing the division by 100 separately and specifying * 0.1725 within the

    calculation.

    If none of the items within the calculation has at least 4 decimal places then the intermediateresult from (a) above will not be accurate, whereas method (b) avoids this problem by ensuringthat the result of the division is stored in a field which has the correct number of decimal places.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    26/39

    ** AUTOREADS in VPLUS

    It has always been the standard within Hewlett-Packard's block-mode screen processing that theuser either presses the ENTER key to process the current screen of data, or presses one of theother function keys to do something else.

    The AUTOREAD facility was provided to cater for those special circumstances where it isnecessary to capture the current screen contents without the user being able to press the ENTERkey - for example, when using the HELP subsystem.

    This facility was NOT provided so that the user could bypass the ENTER key altogether, andshould not be used as such.

    ** The SORT statement

    A SORT can be performed in one of the following ways:

    1. Internally, using the construct:2. SORT .... INPUT PROCEDURE IS .....3. OUTPUT PROCEDURE IS ....4. Internally, using the construct:5. SORT .... USING GIVING 6. Externally, by performing the extract/sort/report phases as separate processes.

    Method (a) may be the fastest, but it requires the most memory as the data requirements of theinput, sort and output procedures are all made available at the same time, which can sometimescause a stack overflow. This construct should therefore be avoided.

    Method (b) ensures that the input procedure (used to extract data onto an intermediate file) iscompleted before the sort is commenced, and that the sort is completed before the outputprocedure (which processes the sorted file) is commenced. This is slightly slower than method(a), but reduces the risk of a stack overflow.

    Method (c) is a further improvement on method (b) insofar as each of the procedures is aseparate program. This is useful if either of the input or output procedures is especially complexas the code is kept entirely separate. If an error occurs then any of the later steps can be rerunwithout having to reprocess all the earlier steps. If different options are required in the outputprocedure then they should be provided in separate programs rather than additional and optionalcode within a single program.

    ** Defining and using Print Files

    Problems can occur with print files if they are not defined correctly within the environmentdivision of a COBOL program. An example of the correct definition is as follows:-

    SELECT ASSIGN TO "external-name,,,LP(CCTL)"

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    27/39

    The LP(CCTL) suffix causes the file to be created with the default device class of "LP" and withthe carriage-control option turned on. Without it the file would be created as a temporary diskfile and would not be printed, and would be lost at the end of the job/session. This has beenknown to cause the client great confusion when he streams a job and the expected print file doesnot appear. The way out of this predicament is to amend the jobstream(s) to include a file equate

    which changes the file's characteristics from a temporary disk file to a spool file.

    The program should use the WRITE AFTER/BEFORE n/TOP-OF-PAGE statement to addrecords to the print file which will automatically insert the correct carriage-control instructions.The practice of defining the file as a serial disk file with an extra character at the beginning tocontain the hard-coded carriage-control value should be avoided.

    ** The ACCEPT statement

    If a program requires a parameter value before it can continue with its processing it is normal

    practice to acquire this from the $STDIN file by means of the ACCEPT verb.

    Before each ACCEPT statement there should be a corresponding DISPLAY statement in order toidentify that some input data is required, and to indicate the format/content that it should take.For example:

    DISPLAY "Enter selection date (DDMMYY): " NO ADVANCING.ACCEPT W01-RUN-DATE.DISPLAY W01-RUN-DATE.

    This should prevent the situation where the program waits for input from the user while the userwaits for instructions from the program.

    If the program is liable to be run in a jobstream then it would be a good idea to follow theACCEPT with a DISPLAY . The $STDLIST output will then show notonly what parameter value that was requested, but also the value that was supplied.

    Sample Online Procedures

    * Introduction

    These standardised COBOL procedures use the VPLUS communication area which is defined in

    COMAREA in the standard copy library (STANDARD.LIB.STANDARD).

    The macro definitions can be found in the macro file STDMACRO.LIB.STANDARD.

    In most situations these procedures replace the need to call all those VPLUS intrinsicsindividually - all the common calls are grouped together and processed in the correct sequence,as and when required. The only intrinsics not included are VPUTBUFFER and VGETBUFFER,because they require the address of a data buffer which is unique for each different form.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    28/39

    These procedures assume the following programming standards:

    1. No appending forms are used, only forms families.2. Each form will contain a standard heading on the top two lines, to be filled with various

    data at run time.

    3.

    The identity of the form to be loaded and processed is hard-coded in each program, andnot taken from any settings in the formsfile. If any form has a value in NFNAME it willbe ignored.

    4. Only those terminals which support function key labels will be used. Function key labelswill be hard-coded, and not taken from any formsfile definition.

    5. Function keys 6,7 and 8 have preset values, as follows:o f6 = PRINT (to print current form)o f7 = HELP (see UHELP subroutine)o f8 = EXIT (terminate current transaction).

    6. All other function keys may be used to select different processing options as and whenthey become available - however, a meaningful description must be placed in the

    corresponding label area.7. Any function key WITHOUT a label is deemed to be invalid, and will display an errormessage if selected.

    8. The window line is never blank - it should always contain some sort of instruction orinformative message. A default message will be used if none is supplied.

    * Standard VPLUS Macros

    The following macros are the most frequently used for VPLUS screen processing. The macrosare obtained from file STDMACRO.[NM]LIB, and are documented in the manual entitledLibrary of Standard COBOL Macros. The subroutines that they call are documented in the

    manual entitledLibrary of Standard Utilities.

    %VGETBUFFER(Para#,Buffer#) Transfers screen buffer to the program's data buffer.

    %VPUTBUFFER(Para#,Buffer#) Transfers program's data buffer to the screen buffer.

    %SAVINITFORM(Para#,Form#) Loads and initialises a new form.

    %ACCEPTENTER(Para#)Displays the current form, window line and function keylabels, then waits for the user to press either the ENTER keyor one of the labelled function keys.

    %ACCEPTFUNCTION(Para#) Similar to %ACCEPTENTER, but will reject the ENTERkey.

    %SCVSETERROR(Para#)Flags field VIEW-FIELD-NAME in error, using the messagein VIEW-WINDOW.

    %SDVPUTFIELD(Para#)Updates the value of a single field in the current screenbuffer without affecting the data in any of the other fields.

    http://www.tonymarston.net/cobol/standardmacros.htmlhttp://www.tonymarston.net/cobol/standardmacros.htmlhttp://www.tonymarston.net/cobol/standardutilities.htmlhttp://www.tonymarston.net/cobol/standardutilities.htmlhttp://www.tonymarston.net/cobol/standardutilities.htmlhttp://www.tonymarston.net/cobol/standardutilities.htmlhttp://www.tonymarston.net/cobol/standardmacros.html
  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    29/39

    %BLINKMSG(Para#)Displays a message in the window line with the blink optionset, and locks the keyboard until the next %ACCEPTENTERor %ACCEPTFUNCTION.

    * Examples** Sample screen processing

    Each screen should be processed separately, as follows:

    C-SCREEN-MA01 SECTION.*************************************************************

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    30/39

    EXIT.

    Here is a sample section which is invoked when the user presses the ENTER key. If the data isvalid the user must press another key to add this data to the database, or he may change any ofthe data and have it validated again.

    CA-ENTER-KEY SECTION.******************************************************************* ENTER key has been pressed - validate data and process it.******************************************************************CA-10-VALIDATE.

    %VGETBUFFER(CA-10#,MA01-BUFFER#).

    PERFORM CAA-VALIDATE-MA01.IF VEDIT-ERRORS

    GO TO CA-EXIT.

    CA-20-CONFIRM.

    MOVE "CANCEL" TO VIEW-LABEL(4).

    * User confirms this data by pressing function key 5%CONFIRMDATA(CA-20#,5#,CA-10-VALIDATE#).

    IF NOT F5MOVE SPACES TO VIEW-LABEL(4)GO TO CA-EXIT.

    CA-30-PROCESS.

    * Processing - please wait

    %BLINKMSG(CA-30#).

    PERFORM CAB-PROCESS-DATA.IF IMAGE-LOCK-FAILURE

    GO TO CA-20-CONFIRMEND-IF.

    CA-EXIT.EXIT.

    Here is a sample validation section. Notice that processing stops on the first error, otherwise thecontents of the window line may not relate to the field where the cursor is positioned.

    CAA-VALIDATE-MA01 SECTION.CAA-10-ITEM-1.

    %DBGET7(CAA-10#,BASE#,SET#,ARG#).

    IF IMAGE-NO-ENTRYMOVE "" TO VIEW-WINDOWMOVE "" TO VIEW-FIELD-NAME%SCVSETERROR(CAA-10#)GO TO CAA-EXIT

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    31/39

    END-IF.

    MOVE TO MA01-.

    CAA-20-ITEM-2.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    32/39

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    33/39

    14.15. * If there is not enough room on the current page for this16. * line (or group of lines) then start a new page.17. IF (LINE-COUNT + LINE-ADVANCE + LINE-GROUP) > MAX-LINES18. PERFORM ZAA-PRINT-HEADING.19.20. * Now print the current line.21. WRITE PRINT-REC FROM PRINT-LINE AFTER LINE-ADVANCE.22.23. * Increment LINE-COUNT and reset LINE-GROUP24. ADD LINE-ADVANCE TO LINE-COUNT.25. MOVE ZERO TO LINE-GROUP.26.27. ZA-EXIT.28. EXIT.29. $PAGE30. ZAA-PRINT-HEADING SECTION.31. **************************************************************32. * Standard module to print page headings.33. **************************************************************34. ZAA-10-NEW-PAGE.35.36. ADD 1 TO PAGE-COUNT.37. MOVE PAGE-COUNT TO H1-PAGE-NO.38.39. IF PAGE-COUNT = 140. * Do not put a blank page at the start of the file41. WRITE PRINT-REC FROM HDG-1 AFTER 042. ELSE43. WRITE PRINT-REC FROM HDG-1 AFTER TOP-OF-PAGE44. END-IF.45.46. WRITE PRINT-REC FROM HDG-2 AFTER 1.47. WRITE PRINT-REC FROM HDG-3 AFTER 2.48. WRITE PRINT-REC FROM HDG-4 AFTER 2.49.50. MOVE 6 TO LINE-COUNT. < this is the position after HDG-4 >51.52. MOVE 3 TO LINE-ADVANCE. < the 1st detail line will always >53. < be 3 lines below the headings >54.55. ZAA-EXIT.56. EXIT.57.Use them in the following manner:

    o You don't need to print the headings on the 1st page after opening the print file,this is done automatically when the first line is printed (this is why LINE-COUNT

    starts off with a value of 99).o If it is possible for the program to produce a null report (ie: no report lines were

    generated) this can be detected in the termination module by the fact that PAGE-COUNT is still zero. A separate flag is not required.

    o When printing detail lines at the lowest level (with single spacing, for example)use the following commands:

    o MOVE TO PRINT-LINE.o PERFORM ZA-PRINT-LINE.o MOVE 1 TO LINE-ADVANCE.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    34/39

    Note that LINE-ADVANCE is set AFTER the call to module ZA - this is to allow forthose cases where the 1st detail line in the current series does not immediatelyfollow the preceding line (a group heading, for example).

    o In the case where a group heading needs to be printed lines after the lastline, and with lines before the 1st detail, use the following commands:o MOVE TO PRINT-LINE.

    o MOVE TO LINE-ADVANCE.o PERFORM ZA-PRINT-LINE.o MOVE TO LINE-ADVANCE.o In those cases where a group heading must start on a fresh page you do not need

    to call module ZAA - it is sufficient to set LINE-COUNT to 99 before callingmodule ZA.

    * Control Breaks with sorted files

    Here is a structured method to process a sorted file which has three levels of data. There is aseparate section for each level (or control break). With this structure it is relatively easy tohandle any number of control breaks.

    FILE SECTION.*SD SORT-FILE.

    01 SORT-REC.03 SR-LEVEL-1 PIC X(20).03 SR-LEVEL-2 PIC X(10).03 SR-LEVEL-3 PIC XX.03 SR-AMOUNT PIC S9(7)V99 COMP.

    *WORKING-STORAGE SECTION.*01 W01-LEVEL-1 PIC X(20).01 W01-LEVEL-1-TOTAL PIC S9(16)V99 COMP.

    01 W02-LEVEL-2 PIC X(10).01 W02-LEVEL-2-TOTAL PIC S9(16)V99 COMP.

    01 W03-LEVEL-3 PIC XX.01 W03-LEVEL-3-TOTAL PIC S9(16)V99 COMP.

    01 W04-REPORT-TOTAL PIC S9(16)V99 COMP.

    Note that in the following sample code the section prefix starts with a single letter rather than agroup of 4 or 5 letters. This is because the report procedure is usually a completely separate step(just like the data extract which built the sorted file) and is not really subordinate to any otherprocessing. The subsequent sections expand this prefix with the addition of a level number ratherthan an ever-increasing set of alphabetic characters. Thus level 4 has a prefix ofF4- rather than

    FABCD-. Any other sections which are performed at a particular level should then follow thenormal method of appending alpha characters to the prefix, eg: F2A-, F2B-, etc.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    35/39

    F-REPORT SECTION.*************************************************************** Report extracted records in LEVEL1/2/3 sequence.**************************************************************F-10-READ-FIRST.

    RETURN SORT-FILEAT END MOVE HIGH-VALUES TO SORT-REC.

    F-20-PROCESS-LEVEL1.

    MOVE ZERO TO W04-REPORT-TOTAL.

    PERFORM F1-REPORT-LEVEL1UNTIL SORT-REC = HIGH-VALUES. >

    F-30-REPORT-END.

    >

    F-EXIT.EXIT.

    $PAGEF1-REPORT-LEVEL1 SECTION.*************************************************************** Process change of LEVEL-1.**************************************************************F1-10-START-LEVEL1.

    * Start each LEVEL-1 on a new pageMOVE 99 TO LINE-COUNT.PERFORM F1A-LEVEL-1-START.

    F1-20-PROCESS-LEVEL2.

    MOVE ZERO TO W01-LEVEL-1-TOTAL.MOVE SR-LEVEL-1 TO W01-LEVEL-1.

    PERFORM F2-REPORT-LEVEL2UNTIL SORT-REC = HIGH-VALUES >OR SR-LEVEL-1 NOT = W01-LEVEL-1.

    F1-30-END-DEPOT.

    PERFORM F1B-LEVEL-1-END.

    ADD W01-LEVEL-1-TOTAL TO W04-REPORT-TOTAL.

    F1-EXIT.EXIT.

    $PAGEF2-REPORT-LEVEL2 SECTION.*************************************************************** Process change of LEVEL-2.**************************************************************F2-10-START-LEVEL2.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    36/39

    >

    F2-20-PROCESS-LEVEL3.

    MOVE ZERO TO W02-LEVEL-2-TOTAL.MOVE SR-LEVEL-2 TO W02-LEVEL-2.

    PERFORM F3-REPORT-LEVEL3UNTIL SORT-REC = HIGH-VALUES >OR SR-LEVEL-1 NOT = W01-LEVEL-1OR SR-LEVEL-2 NOT = W02-LEVEL-2.

    F2-30-END-LEVEL2.

    >

    ADD W02-LEVEL-2-TOTAL TO W01-LEVEL-1-TOTAL.

    F2-EXIT.EXIT.

    $PAGEF3-REPORT-LEVEL3 SECTION.*************************************************************** Process change of LEVEL-3.**************************************************************F3-10-START-LEVEL3.

    >

    F3-20-PROCESS-LEVEL3.

    MOVE ZERO TO W03-LEVEL-3-TOTAL.MOVE SR-LEVEL-3 TO W03-LEVEL-3.

    PERFORM F4-ACCUMULATE-LEVEL4UNTIL SORT-REC = HIGH-VALUES >OR SR-LEVEL-1 NOT = W01-LEVEL-1OR SR-LEVEL-2 NOT = W02-LEVEL-2OR SR-LEVEL-3 NOT = W03-LEVEL-3.

    F3-30-END-LEVEL3.

    >

    ADD W03-LEVEL-3-TOTAL TO W02-LEVEL-2-TOTAL.

    F3-EXIT.

    EXIT.$PAGEF4-ACCUMULATE-LEVEL4 SECTION.*************************************************************** Accumulate all amounts into W03-LEVEL-3-TOTAL.**************************************************************F4-10-ACCUMULATE.

    ADD SR-AMOUNT TO W03-LEVEL-3-TOTAL.

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    37/39

    F4-20-READ-NEXT.

    RETURN SORT-FILE AT ENDMOVE HIGH-VALUES TO SORT-REC.

    F4-EXIT.EXIT.

    Programming Hints

    * Multi-line Enquiry screens

    It is quite common for some enquiry screens to be constructed using repeating data, eg: to list allinvoices for a customer, or to list lines within an invoice. In these cases multiple records areaccessed (usually from a detail chain on an IMAGE database), and each record is loaded into one

    line on the screen. Here are some tips that may prove useful:

    FORMSPEC definition

    Each detail line on the screen will contain several items of data, and it would seem logical todefine each data item as a separate field on the screen. However, this could lead to the formcontaining a very large number of fields, as in the following example:

    DOCNO_01 DATE_01. DESCRIPTION_01................ VALUE_01.... VAT_01.DOCNO_02 DATE_02. DESCRIPTION_02................ VALUE_02.... VAT_02.

    " " " " "" " " " "

    DOCNO_10 DATE_10. DESCRIPTION_10................ VALUE_10.... VAT_10.

    An easier option would be to define each line as a single field on the screen and have theprogram split each line down into its component parts, as in the following example:

    LINE_01..............................................................LINE_02..............................................................

    " " " " "" " " " "

    LINE_10..............................................................

    This cuts down the time used to build and maintain the screen as the 10 lines contain just 10

    fields instead of 50, and also cuts down the size of the form within the formsfile as there arefewer fields that require start/end delimiters. The only overhead is within the program as thedefinition for each line must now contain the spaces between each data item.

    Overflow data

    It has been known that the amount of data available for each entity is too large to fit onto a single80-column line on the screen. One way around this problem would be to take up two lines for

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    38/39

    each entity, but this would cut in half the number of entities that could be shown on a singlescreen.

    Another option would be to stick to the single line per entity and split the amount of data to bedisplayed for each entity into two or more sets. By providing the user with a special function key

    he can then "toggle" between the different sets of data. By changing the column headings fromhard-coded text on the form into a data field it would then be possible for the program to changethe headings to suit the data being displayed.

    When the program reads the data for each entity it should load it into an intermediate storagearea and not directly into the screen buffer. There should then be a separate section to transfereach different set of data from this intermediate area into the screen buffer depending on thesetting of the "toggle" switch.

    Paging between screens

    As it is only possible to display one screenfull of data at a time it is usual practice to supply

    function keys which allow the user to move forwards to the next page or backwards to theprevious page. This is easily done when reading from an IMAGE detail dataset as it is possible toread both forward and backwards, and to reposition at any record within the chain.

    Various methods have been used to implement the paging functions, but the most successful onefollows these lines:

    1. When reading from the detail chain into a program array additional areas are required tostore the addresses of the first and last records on the current screen.

    2. The section which loads the next page should do the following:o Reposition the chain pointer (using %DBGET4) to the address of the last record on

    the current screen.o Do a forward chained read (%DBGET5).o Load details into the screen buffer from the top down.

    3. The section which loads the previous page should do the following:o Reposition the chain pointer to the address of the first record on the current

    screen.

    o Do a backward chained read (%DBGET6).o Load details into the screen buffer from the bottom up.

    * Multi-line Input/Update screens

    Where an input/update function has room for an array of entities on the screen it can be quitecomplicated to allow the user to access the whole of the array to add, amend or delete differentrecords. One very versatile method is to make the bulk of the array into display-only fields(similar to the enquiry function in the previous section) and to restrict all modifications to the lastline on the screen (known as the "action" line).

  • 8/3/2019 Bilal Ahmed Shaik-COBOL Programming STD

    39/39

    Two additional fields will be normally be required on this "action" line - one to identify therecord to be manipulated, and another to identify the mode (Add, Change or Delete).

    This means that only one record at a time can me manipulated, but the display-only block abovethe "action" line would have room to show the details of other records, with function key options

    to load the previous or next page of records as in the enquiry function.

    The program code to handle each action mode would be as follows:

    AddValidate for a new record, add to database, transfer details to next available blank linein the display area, or scroll the existing details up to make room on the last displayline.

    UpdateLoad details of the selected record into the action line, allow the user to makeamendments, then overwrite details in the screen area with the new values.

    Delete

    Load details of the selected record into the action line, and if confirmed delete the

    record from the database and blank out the corresponding line in the display area.

    It would be necessary to store the IMAGE record addresses for all the records in the currentscreen, as well as the first and last records, as the Update and Delete procedures would be

    required to re-read the selected records (using %DBGET4) before they could be updated or deleted.

    If either of the first/last records in the current screen were deleted the stored record addressesused for the next/previous page functions would have to be modified to reflect the actual first/last

    records after the deletion has taken place, otherwise the %DBGET4 would be given a recordaddress that does not exist, and would cause the program to abort.