MainframeMaster

COBOL Tutorial

COBOL Coding Standards

Progress0 of 0 lessons

Introduction to COBOL Coding Standards

COBOL coding standards provide guidelines for writing clear, maintainable, and consistent code. Following these standards becomes especially important when multiple developers work on the same codebase or when programs need to be maintained over many years or even decades.

Benefits of Coding Standards

  • Improved readability and understandability of the code
  • Easier maintenance and debugging
  • Reduced learning curve for new team members
  • Consistent quality across the entire codebase
  • More efficient code reviews
  • Reduced risk of errors and bugs
  • Better knowledge transfer during staff transitions

Key Components of COBOL Coding Standards

ComponentDescription
Naming ConventionsRules for naming variables, procedures, and modules
Documentation StandardsGuidelines for program headers, comments, and documentation
Formatting GuidelinesStandards for indentation, spacing, and layout
Modular ProgrammingTechniques for structuring code into logical, reusable modules
Self-Documenting CodePractices that make code more intuitive without excessive comments

Naming Conventions

Naming conventions provide consistency and clarity in how program elements are named. Well-chosen names communicate the purpose and usage of variables, paragraphs, sections, and programs, making the code easier to understand and maintain.

General Naming Principles

  • Make names descriptive and meaningful
  • Use consistent conventions throughout the program
  • Balance descriptiveness with reasonable length
  • Use hyphens to separate words in compound names
  • Use uppercase for traditional COBOL environments
  • Avoid generic or ambiguous names
  • Use standard prefixes and suffixes for clarity

Data Item Naming

Data items should be named according to these guidelines:

ElementNaming ConventionExamples
Working Storage ItemsPrefix with WS- and use descriptive namesWS-COUNTER, WS-EMPLOYEE-NAME
File Description ItemsPrefix with file name abbreviationCUST-ID, EMP-SALARY
Flags/IndicatorsUse -FLAG, -SW (switch), or -IND (indicator) suffixEOF-FLAG, VALID-DATA-SW
CountersUse -COUNT, -CTR, or -COUNTER suffixRECORD-COUNT, ERROR-CTR
Numeric TotalsUse -TOTAL, -SUM, or -AMT suffixINVOICE-TOTAL, SALES-AMT
Tables/ArraysUse -TABLE suffix or plural formPRODUCT-TABLE, EMPLOYEES
Table IndexesUse -IDX or -INDEX suffix with table namePRODUCT-IDX, EMPLOYEE-INDEX
Condition Names (88)Use descriptive state namesVALID-CUSTOMER, FILE-IS-OPEN

Program, Section, and Paragraph Naming

ElementNaming ConventionExamples
ProgramsShort, descriptive name indicating purposeCUSTMNT (Customer Maintenance), INVPROC (Invoice Processing)
SectionsDescriptive with -SECTION suffix (optional)MAIN-PROCESSING, FILE-HANDLING-SECTION
ParagraphsVerb-noun combination describing actionPROCESS-CUSTOMER, CALCULATE-TOTALS
Initialization ParagraphsPrefix with INIT- or INITIALIZE-INIT-PROGRAM, INITIALIZE-VARIABLES
Exit/Termination ParagraphsPrefix with EXIT- or TERMINATE-EXIT-PROGRAM, TERMINATE-PROCESSING

Example of Consistent Naming

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
IDENTIFICATION DIVISION. PROGRAM-ID. CUSTMNT. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CUSTOMER-FILE ASSIGN TO CUSTFILE ORGANIZATION IS INDEXED ACCESS MODE IS DYNAMIC RECORD KEY IS CUST-ID. DATA DIVISION. FILE SECTION. FD CUSTOMER-FILE. 01 CUSTOMER-RECORD. 05 CUST-ID PIC X(6). 05 CUST-NAME PIC X(30). 05 CUST-ADDRESS PIC X(50). 05 CUST-TYPE PIC X. 88 CUST-RETAIL VALUE 'R'. 88 CUST-WHOLESALE VALUE 'W'. 05 CUST-STATUS PIC X. 88 CUST-ACTIVE VALUE 'A'. 88 CUST-INACTIVE VALUE 'I'. 88 CUST-SUSPENDED VALUE 'S'. WORKING-STORAGE SECTION. 01 WS-FLAGS. 05 WS-EOF-FLAG PIC X VALUE 'N'. 88 WS-END-OF-FILE VALUE 'Y'. 05 WS-VALID-DATA-SW PIC X VALUE 'N'. 88 WS-VALID-DATA VALUE 'Y'. 01 WS-COUNTERS. 05 WS-RECORDS-READ PIC 9(5) VALUE ZEROS. 05 WS-UPDATE-COUNT PIC 9(5) VALUE ZEROS. 05 WS-ERROR-COUNT PIC 9(5) VALUE ZEROS. PROCEDURE DIVISION. MAIN-CONTROL SECTION. PERFORM INITIALIZE-PROGRAM PERFORM PROCESS-CUSTOMERS UNTIL WS-END-OF-FILE PERFORM TERMINATE-PROGRAM STOP RUN. INITIALIZE-PROGRAM. OPEN I-O CUSTOMER-FILE PERFORM READ-FIRST-CUSTOMER. PROCESS-CUSTOMERS. PERFORM VALIDATE-CUSTOMER-DATA IF WS-VALID-DATA PERFORM UPDATE-CUSTOMER-RECORD ADD 1 TO WS-UPDATE-COUNT ELSE ADD 1 TO WS-ERROR-COUNT END-IF PERFORM READ-NEXT-CUSTOMER. READ-FIRST-CUSTOMER. READ CUSTOMER-FILE NEXT RECORD AT END SET WS-END-OF-FILE TO TRUE END-READ ADD 1 TO WS-RECORDS-READ. READ-NEXT-CUSTOMER. READ CUSTOMER-FILE NEXT RECORD AT END SET WS-END-OF-FILE TO TRUE END-READ ADD 1 TO WS-RECORDS-READ. VALIDATE-CUSTOMER-DATA. SET WS-VALID-DATA TO TRUE IF CUST-NAME = SPACES SET WS-VALID-DATA TO FALSE END-IF. UPDATE-CUSTOMER-RECORD. * Update logic would go here REWRITE CUSTOMER-RECORD. TERMINATE-PROGRAM. CLOSE CUSTOMER-FILE DISPLAY "Records read: " WS-RECORDS-READ DISPLAY "Records updated: " WS-UPDATE-COUNT DISPLAY "Errors found: " WS-ERROR-COUNT.

This example demonstrates consistent naming conventions throughout the program, from file and record names to working storage items, flags, and procedure names. Note how each name clearly indicates its purpose and how prefixes and suffixes help distinguish different types of data items.

Documentation Standards

Documentation standards ensure that COBOL programs are well-documented, making them easier to understand, maintain, and modify. Good documentation explains program purpose, logic, assumptions, and business rules that might not be immediately obvious from the code itself.

Program Header Documentation

Every COBOL program should begin with a comprehensive header comment:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
***************************************************************** * PROGRAM ID: INVPROC * * * * DESCRIPTION: Invoice Processing Program. * * Processes daily invoice transactions and * * updates master customer file. * * * * INPUTS: INVTRAN - Daily invoice transaction file * * CUSTMAST - Customer master file * * * * OUTPUTS: CUSTMAST - Updated customer master file * * INVPROC-REPORT - Processing report * * * * AUTHOR: Jane Smith * * DATE: 2023-05-15 * * * * MAINTENANCE: * * DATE PERSON DESCRIPTION * * ---------- ------ ----------------------------------------- * * 2023-06-10 JDS Added credit limit validation check * * 2023-07-22 JDS Modified report format per user request * * 2023-09-15 TJR Added error handling for missing records * *****************************************************************

The program header should include:

  • Program ID and name
  • Detailed description of program purpose
  • Input and output files or data sources
  • Author name and creation date
  • Maintenance history with dates, initials, and change descriptions
  • Any special considerations or dependencies

Section and Paragraph Documentation

Sections and paragraphs should be documented to explain their purpose and logic:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
***************************************************************** * VALIDATE-CUSTOMER Section * * Performs validation checks on customer data. * * Validates customer ID, name, and credit limit. * * Sets WS-VALID-CUSTOMER flag based on validation results. * ***************************************************************** VALIDATE-CUSTOMER SECTION. SET WS-VALID-CUSTOMER TO TRUE. * Check if customer ID is valid IF CUST-ID = SPACES OR CUST-ID = ZEROS DISPLAY "Error: Invalid Customer ID" SET WS-VALID-CUSTOMER TO FALSE END-IF. * Verify customer name is not blank IF CUST-NAME = SPACES DISPLAY "Error: Customer name cannot be blank" SET WS-VALID-CUSTOMER TO FALSE END-IF. * Verify credit limit is within acceptable range IF CUST-CREDIT-LIMIT < 0 OR CUST-CREDIT-LIMIT > 100000 DISPLAY "Error: Credit limit out of acceptable range" SET WS-VALID-CUSTOMER TO FALSE END-IF.

Section and paragraph comments should include:

  • Purpose and function of the section/paragraph
  • Description of the logic being implemented
  • Input parameters or data used
  • Output or side effects
  • Any special conditions or exceptions handled

Inline Documentation

In-line comments should be used judiciously to explain complex logic, business rules, or non-obvious decisions:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
* Apply discount based on customer type and order amount COMPUTE WS-DISCOUNT-AMOUNT = 0. EVALUATE TRUE WHEN CUST-PREFERRED AND ORDER-AMOUNT > 1000 * Preferred customers get 15% discount on orders over $1000 COMPUTE WS-DISCOUNT-AMOUNT = ORDER-AMOUNT * 0.15 WHEN CUST-PREFERRED * Preferred customers get 10% discount on all other orders COMPUTE WS-DISCOUNT-AMOUNT = ORDER-AMOUNT * 0.10 WHEN ORDER-AMOUNT > 5000 * Regular customers get 8% discount on orders over $5000 COMPUTE WS-DISCOUNT-AMOUNT = ORDER-AMOUNT * 0.08 WHEN ORDER-AMOUNT > 1000 * Regular customers get 5% discount on orders over $1000 COMPUTE WS-DISCOUNT-AMOUNT = ORDER-AMOUNT * 0.05 END-EVALUATE. * Round discount to nearest cent (business requirement #BR-2468) COMPUTE WS-DISCOUNT-AMOUNT ROUNDED = WS-DISCOUNT-AMOUNT.

Effective inline comments should:

  • Explain "why" rather than "what" (the code already shows what is happening)
  • Document business rules and their sources
  • Explain complex algorithms or calculations
  • Note assumptions or limitations
  • Reference requirement IDs or business rules when applicable
  • Avoid stating the obvious (e.g., "Add 1 to counter" is redundant for "ADD 1 TO COUNTER")

Formatting Guidelines

Consistent code formatting improves readability and makes it easier to navigate through COBOL programs. Good formatting practices make the structure and logic of the program visually apparent and reduce the cognitive load when reading the code.

Indentation and Structure

Proper indentation helps to visually represent the hierarchical structure of COBOL code:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
IDENTIFICATION DIVISION. PROGRAM-ID. STRUCTURED-CODE. PROCEDURE DIVISION. MAIN-LOGIC. PERFORM INITIALIZATION PERFORM PROCESS-DATA UNTIL END-OF-FILE PERFORM FINALIZATION STOP RUN. INITIALIZATION. OPEN INPUT CUSTOMER-FILE OUTPUT REPORT-FILE PERFORM READ-FIRST-RECORD. PROCESS-DATA. IF VALID-CUSTOMER-RECORD PERFORM PROCESS-CUSTOMER ELSE PERFORM HANDLE-INVALID-RECORD END-IF PERFORM READ-NEXT-RECORD. PROCESS-CUSTOMER. MOVE SPACES TO REPORT-LINE MOVE CUSTOMER-ID TO RL-CUSTOMER-ID MOVE CUSTOMER-NAME TO RL-CUSTOMER-NAME IF CUSTOMER-BALANCE > ZERO COMPUTE RL-AMOUNT = CUSTOMER-BALANCE * 1.05 WRITE REPORT-RECORD END-IF.
  • Division headers and section names start at the left margin (Area A)
  • Paragraph names also begin in Area A
  • Statements within paragraphs are indented consistently (typically 4 spaces)
  • Nested statements receive additional indentation to show their scope
  • Related elements are aligned vertically for better readability

Spacing and Alignment

ElementFormatting Practice
Division HeadersFollowed by a blank line for visual separation
Section HeadersPreceded by a blank line to create visual separation
Paragraph NamesPreceded by a blank line except when immediately following a section header
Data DefinitionsAlign level numbers, data names, PIC clauses, and VALUE clauses in columns
Conditional StatementsUse consistent spacing around operators (=, >, <) and logical connectors (AND, OR)
Statement GroupsGroup related statements together with blank lines between logical groups

Column Alignment in DATA DIVISION

Proper alignment in the DATA DIVISION improves readability:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
DATA DIVISION. WORKING-STORAGE SECTION. 01 CUSTOMER-RECORD. 05 CUSTOMER-ID PIC 9(6). 05 CUSTOMER-NAME PIC X(30). 05 CUSTOMER-ADDRESS. 10 STREET-ADDRESS PIC X(25). 10 CITY PIC X(20). 10 STATE PIC XX. 10 ZIP-CODE PIC 9(5). 05 CUSTOMER-DETAILS. 10 ACCOUNT-NUMBER PIC X(10). 10 CREDIT-LIMIT PIC 9(7)V99. 10 CURRENT-BALANCE PIC S9(7)V99. 10 LAST-PAYMENT-DATE PIC 9(8). 01 FLAGS-AND-INDICATORS. 05 EOF-FLAG PIC X VALUE 'N'. 88 END-OF-FILE VALUE 'Y'. 05 VALID-RECORD-FLAG PIC X VALUE 'Y'. 88 VALID-RECORD VALUE 'Y'. 88 INVALID-RECORD VALUE 'N'. 05 RECORD-COUNT PIC 9(6) VALUE ZERO.

Note how the level numbers, data names, PIC clauses, and VALUE clauses are aligned in columns. This vertical alignment makes it easier to scan the data definitions and understand the structure.

Modern vs. Traditional Formatting

COBOL code can be formatted in fixed-format (traditional) or free-format (modern) style:

FormatCharacteristicsWhen to Use
Fixed Format
  • Sequence numbers in columns 1-6
  • Indicator area in column 7
  • Area A in columns 8-11
  • Area B in columns 12-72
  • Identification area in columns 73-80
  • Legacy mainframe environments
  • When compatibility with older compilers is needed
  • When maintaining existing fixed-format code
Free Format
  • No column restrictions
  • Code can start anywhere on the line
  • Statements can extend across multiple lines
  • Comments start with '*>' anywhere on the line
  • Modern COBOL environments
  • New development projects
  • When using modern IDEs

Modular Programming Approach

Modular programming in COBOL involves breaking a program into smaller, logical, and manageable components or modules. Each module performs a specific function and can be developed, tested, and maintained independently. This approach enhances program structure, readability, and reusability.

Principles of Modular Programming

  • Single Responsibility: Each module should have one clearly defined purpose
  • Information Hiding: Modules should only expose necessary interfaces
  • Low Coupling: Minimize dependencies between modules
  • High Cohesion: Related functionality should be grouped together
  • Reusability: Modules should be designed for potential reuse
  • Maintainability: Changes to one module should not affect others

Modularization Techniques in COBOL

TechniqueDescriptionBest Used For
ParagraphsSimplest form of modules; named sections of code that can be invoked with PERFORMSmall, simple operations within a program
SectionsGroups of related paragraphs that form a logical unitOrganizing related operations within a program
SubprogramsSeparate COBOL programs that can be called from other programsReusable functionality across multiple programs
CopybooksExternal source code included in the program during compilationSharing common data definitions or procedures
Called ProgramsExternal programs invoked using the CALL statementComplex, independent functionality

Example: Modular Program Structure

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
IDENTIFICATION DIVISION. PROGRAM-ID. MODULAR-EXAMPLE. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. COPY STDFILES. *> Copybook containing standard file definitions DATA DIVISION. FILE SECTION. COPY FILEDEF. *> Copybook containing file record layouts WORKING-STORAGE SECTION. COPY WSVARS. *> Copybook containing common variables 01 PROGRAM-FLAGS. 05 EOF-FLAG PIC X VALUE 'N'. 88 END-OF-FILE VALUE 'Y'. PROCEDURE DIVISION. 0000-MAIN-LOGIC. PERFORM 1000-INITIALIZATION PERFORM 2000-PROCESS-DATA UNTIL END-OF-FILE PERFORM 3000-TERMINATION STOP RUN. *> Initialization module 1000-INITIALIZATION. DISPLAY "Starting program execution" PERFORM 1100-OPEN-FILES PERFORM 1200-READ-FIRST-RECORD. 1100-OPEN-FILES. OPEN INPUT CUSTOMER-FILE OUTPUT REPORT-FILE. 1200-READ-FIRST-RECORD. READ CUSTOMER-FILE AT END SET END-OF-FILE TO TRUE END-READ. *> Processing module 2000-PROCESS-DATA. EVALUATE TRUE WHEN VALID-CUSTOMER PERFORM 2100-PROCESS-VALID-CUSTOMER WHEN INACTIVE-CUSTOMER PERFORM 2200-PROCESS-INACTIVE-CUSTOMER WHEN OTHER PERFORM 2300-PROCESS-INVALID-RECORD END-EVALUATE PERFORM 2900-READ-NEXT-RECORD. 2100-PROCESS-VALID-CUSTOMER. CALL 'CUSTPROC' USING CUSTOMER-RECORD, REPORT-RECORD PERFORM 2110-WRITE-REPORT-RECORD. *> Additional processing paragraphs... 2900-READ-NEXT-RECORD. READ CUSTOMER-FILE AT END SET END-OF-FILE TO TRUE END-READ. *> Termination module 3000-TERMINATION. CLOSE CUSTOMER-FILE REPORT-FILE DISPLAY "Program completed successfully" DISPLAY "Processed " RECORD-COUNT " records" .

This example demonstrates several modular programming techniques:

  • Using copybooks for common data definitions and file declarations
  • Organizing code into functional sections (initialization, processing, termination)
  • Breaking down operations into specific paragraphs with clear purposes
  • Using a consistent numbering convention for paragraph names
  • Calling external subprograms for specialized processing

Module Design Guidelines

When designing modules in COBOL, follow these guidelines:

  1. Size: Modules should typically be 50-200 lines of code; larger modules should be subdivided
  2. Entry/Exit Points: Each module should have a single entry point and preferably a single exit point
  3. Interface: Clearly define the data passed to and from each module
  4. Naming: Use a consistent naming convention that reflects the module's purpose and level in the hierarchy
  5. Documentation: Document the purpose, inputs, outputs, and assumptions for each module
  6. Independence: Design modules to be as independent as possible from other modules
  7. Parameter Passing: Use the LINKAGE SECTION and USING clause for passing data between programs
  8. Error Handling: Include appropriate error handling within each module

Benefits of Modular COBOL Programming

Development Benefits

  • Parallel development by multiple programmers
  • Easier unit testing of individual components
  • Reduced complexity through decomposition
  • Code reuse across multiple programs
  • Better project planning and task allocation

Maintenance Benefits

  • Isolated changes with minimal side effects
  • Easier to locate and fix bugs
  • Simplified knowledge transfer to new developers
  • Better adaptability to changing requirements
  • Reduced regression testing scope for changes

Self-Documenting Code Techniques

Self-documenting code is code that clearly communicates its intent through careful design, meaningful naming, and logical structure, reducing the need for extensive comments. Well-written COBOL code should be largely self-explanatory, making it easier to understand and maintain.

Core Principles of Self-Documenting COBOL

  • Meaningful Names: Use descriptive identifiers that express purpose and intent
  • Logical Organization: Structure code in a way that follows natural problem-solving patterns
  • Consistent Patterns: Apply consistent coding styles and patterns throughout the program
  • Appropriate Abstractions: Create modules at the right level of abstraction for the problem domain
  • Minimal Complexity: Keep code as simple as possible while fulfilling requirements
  • Explicit Intent: Make the purpose of each code element obvious

Descriptive Naming Examples

Poor NamingSelf-Documenting NamingImprovement
P1CALCULATE-MONTHLY-PAYMENTClearly communicates the paragraph's purpose
FLGVALID-TRANSACTION-FLAGIndicates what the flag represents
AMT1GROSS-SALARY-AMOUNTSpecifies which amount and its type
CTREMPLOYEE-RECORD-COUNTERIndicates what is being counted
PRCS-RECPROCESS-CUSTOMER-RECORDUses complete words for clarity

Condition Names (88-Level)

Using 88-level condition names makes code more readable and self-documenting:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
*> Instead of this: IF CUSTOMER-STATUS = 'A' PERFORM PROCESS-ACTIVE-CUSTOMER ELSE IF CUSTOMER-STATUS = 'I' PERFORM PROCESS-INACTIVE-CUSTOMER END-IF *> Use this: 01 CUSTOMER-DETAILS. 05 CUSTOMER-STATUS PIC X. 88 ACTIVE-CUSTOMER VALUE 'A'. 88 INACTIVE-CUSTOMER VALUE 'I'. 88 NEW-CUSTOMER VALUE 'N'. 88 CLOSED-ACCOUNT VALUE 'C'. *> Which enables this clear code: IF ACTIVE-CUSTOMER PERFORM PROCESS-ACTIVE-CUSTOMER ELSE IF INACTIVE-CUSTOMER PERFORM PROCESS-INACTIVE-CUSTOMER END-IF

The 88-level condition names serve as self-documenting boolean tests, making the code more readable and resilient to changes in the underlying values.

Clear Logical Structure

Organizing code in a logical structure enhances self-documentation:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
*> Poorly structured, hard to follow: PROCESS-RECORDS. READ INPUT-FILE AT END MOVE 'Y' TO EOF-FLAG END-READ IF EOF-FLAG NOT = 'Y' IF RECORD-TYPE = 'C' MOVE CORR INPUT-RECORD TO CUSTOMER-RECORD WRITE CUSTOMER-RECORD ADD 1 TO CUSTOMER-COUNT ELSE IF RECORD-TYPE = 'O' MOVE CORR INPUT-RECORD TO ORDER-RECORD WRITE ORDER-RECORD ADD 1 TO ORDER-COUNT ELSE ADD 1 TO ERROR-COUNT END-IF END-IF GO TO PROCESS-RECORDS END-IF. *> Better structured, self-documenting: PROCESS-RECORDS. PERFORM UNTIL END-OF-FILE PERFORM READ-NEXT-RECORD IF NOT END-OF-FILE EVALUATE RECORD-TYPE WHEN 'C' PERFORM PROCESS-CUSTOMER-RECORD WHEN 'O' PERFORM PROCESS-ORDER-RECORD WHEN OTHER PERFORM PROCESS-ERROR-RECORD END-EVALUATE END-IF END-PERFORM. READ-NEXT-RECORD. READ INPUT-FILE AT END SET END-OF-FILE TO TRUE END-READ. PROCESS-CUSTOMER-RECORD. MOVE CORRESPONDING INPUT-RECORD TO CUSTOMER-RECORD WRITE CUSTOMER-RECORD ADD 1 TO CUSTOMER-COUNT. PROCESS-ORDER-RECORD. MOVE CORRESPONDING INPUT-RECORD TO ORDER-RECORD WRITE ORDER-RECORD ADD 1 TO ORDER-COUNT. PROCESS-ERROR-RECORD. ADD 1 TO ERROR-COUNT.

The second example is more self-documenting because:

  • It uses structured programming techniques with a clear flow
  • Each paragraph has a specific, well-defined purpose
  • The EVALUATE statement clearly shows the different cases
  • Nested logic is simplified through modularization
  • There are no hard-to-follow GO TO statements

Strategic Comments

Even with self-documenting code, strategic comments are valuable in certain cases:

Comment TypeWhen to Use
Business Rules
cobol
1
2
3
4
5
6
7
8
9
* Per policy HR-103: Employees with 5+ years service * receive an additional 0.5% retirement contribution IF YEARS-OF-SERVICE >= 5 COMPUTE RETIREMENT-CONTRIB = SALARY * (BASE-CONTRIB-RATE + 0.005) ELSE COMPUTE RETIREMENT-CONTRIB = SALARY * BASE-CONTRIB-RATE END-IF
Complex Algorithms
cobol
1
2
3
4
5
6
* Calculate weighted average score using * 30% quiz, 30% midterm, 40% final formula COMPUTE FINAL-GRADE = (QUIZ-SCORE * 0.3) + (MIDTERM-SCORE * 0.3) + (FINAL-SCORE * 0.4)
Performance Optimizations
cobol
1
2
3
4
5
6
* Using binary search algorithm for performance * since the table is guaranteed to be sorted PERFORM VARYING MID-POINT FROM 1 BY 1 UNTIL MID-POINT > TABLE-SIZE *...binary search implementation...* END-PERFORM
Non-Obvious Workarounds
cobol
1
2
3
4
5
* Adding 1 day to CURRENT-DATE to work around * system date issue #CR-12345 COMPUTE WS-DATE-NUM = FUNCTION INTEGER-OF-DATE( FUNCTION DATE-OF-INTEGER( FUNCTION INTEGER-OF-DATE(WS-CURRENT-DATE)) + 1)

Tips for Writing Self-Documenting COBOL

  1. Use the scope terminators (END-IF, END-PERFORM, etc.) to clearly show where blocks end
  2. Choose EVALUATE over nested IF statements when dealing with multiple conditions
  3. Use PERFORM...UNTIL instead of paragraph-level loops with GO TO statements
  4. Group related data items together under meaningful group items
  5. Use COPY statements to include standard code components with recognizable names
  6. Organize paragraphs in a logical, top-down sequence that follows the program flow
  7. Use CORRESPONDING/CORR to make field mappings clearer
  8. Consider table and field names that reflect business terminology
  9. Use level-88 condition names liberally to express business rules
  10. Include units of measure in names where appropriate (e.g., AMOUNT-IN-DOLLARS)

Self-Documenting vs. Over-Commenting

Over-CommentedSelf-Documenting
cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
* Initialize the counter MOVE ZERO TO CTR * Read the first record READ INP-FILE * Check for end of file AT END MOVE 'Y' TO EOF * Process records PERFORM UNTIL EOF = 'Y' * Add 1 to counter ADD 1 TO CTR * Read next record READ INP-FILE * Check for end of file again AT END MOVE 'Y' TO EOF END-READ END-PERFORM
cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
INITIALIZE RECORD-COUNTER READ INPUT-FILE AT END SET END-OF-FILE TO TRUE END-READ PERFORM UNTIL END-OF-FILE ADD 1 TO RECORD-COUNTER READ INPUT-FILE AT END SET END-OF-FILE TO TRUE END-READ END-PERFORM

The self-documenting version uses meaningful names, clearly structured code, and condition names to express intent without needing comments that simply restate what the code is doing.

Test Your Knowledge

1. Why are naming conventions important in COBOL programs?

  • They affect program execution speed
  • They make programs easier to understand and maintain
  • They are required by the COBOL compiler
  • They reduce the memory usage of programs

2. What is a recommended practice for COBOL variable naming?

  • Use single-letter variable names for efficiency
  • Use the same name for different variables in different routines
  • Use hyphens to separate words in compound names (e.g., CUSTOMER-NAME)
  • Always use all lowercase letters for variable names

3. What is a key aspect of self-documenting code in COBOL?

  • Adding comments to every line of code
  • Using meaningful and descriptive data and procedure names
  • Describing everything in the REMARKS paragraph
  • Keeping all variable names under 8 characters

4. What is the purpose of modular programming in COBOL?

  • To reduce compilation time
  • To break down complex programs into manageable, reusable components
  • To reduce memory usage in mainframe environments
  • To avoid using the PROCEDURE DIVISION

5. Which of the following is a good practice for COBOL code formatting?

  • Placing as many statements as possible on a single line
  • Using appropriate indentation to show program structure
  • Avoiding all blank lines to keep programs compact
  • Using Area A (columns 8-11) for all code

Exercises

Exercise 1: Improve Variable Naming

Rewrite the following data definitions using more descriptive and self-documenting names:

cobol
1
2
3
4
5
6
7
8
9
10
01 REC1. 05 FLD1 PIC X(5). 05 FLD2 PIC 9(6). 05 FLD3 PIC X(25). 05 FLD4 PIC 9(8). 05 FLD5 PIC 9(7)V99. 01 CNTR PIC 9(4) VALUE ZERO. 01 F PIC X VALUE 'N'. 01 ST PIC 99 VALUE ZERO.
Solution
cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
01 CUSTOMER-RECORD. 05 CUSTOMER-ID PIC X(5). 05 ACCOUNT-NUMBER PIC 9(6). 05 CUSTOMER-NAME PIC X(25). 05 BIRTH-DATE PIC 9(8). 05 ACCOUNT-BALANCE PIC 9(7)V99. 01 RECORD-COUNTER PIC 9(4) VALUE ZERO. 01 EOF-FLAG PIC X VALUE 'N'. 88 END-OF-FILE VALUE 'Y'. 01 STATUS-CODE PIC 99 VALUE ZERO. 88 STATUS-SUCCESS VALUE 0. 88 STATUS-NOT-FOUND VALUE 10. 88 STATUS-ERROR VALUE 99.

Exercise 2: Refactor for Modularity

Refactor the following monolithic code into well-structured, modular code with appropriate paragraphs:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
PROCEDURE DIVISION. MAIN-LOGIC. OPEN INPUT CUSTOMER-FILE OUTPUT REPORT-FILE READ CUSTOMER-FILE AT END MOVE 'Y' TO EOF-FLAG END-READ PERFORM UNTIL EOF-FLAG = 'Y' MOVE SPACES TO REPORT-RECORD MOVE CUSTOMER-NAME TO REPORT-NAME MOVE CUSTOMER-ID TO REPORT-ID IF ACCOUNT-TYPE = 'S' COMPUTE INTEREST = BALANCE * 0.02 ELSE IF ACCOUNT-TYPE = 'C' COMPUTE INTEREST = BALANCE * 0.01 ELSE MOVE 0 TO INTEREST END-IF END-IF ADD INTEREST TO BALANCE MOVE BALANCE TO REPORT-BALANCE MOVE INTEREST TO REPORT-INTEREST WRITE REPORT-RECORD READ CUSTOMER-FILE AT END MOVE 'Y' TO EOF-FLAG END-READ END-PERFORM CLOSE CUSTOMER-FILE REPORT-FILE STOP RUN.
Solution
cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
PROCEDURE DIVISION. MAIN-LOGIC. PERFORM 1000-INITIALIZATION PERFORM 2000-PROCESS-RECORDS UNTIL END-OF-FILE PERFORM 3000-TERMINATION STOP RUN. 1000-INITIALIZATION. OPEN INPUT CUSTOMER-FILE OUTPUT REPORT-FILE PERFORM 1100-READ-FIRST-RECORD. 1100-READ-FIRST-RECORD. READ CUSTOMER-FILE AT END SET END-OF-FILE TO TRUE END-READ. 2000-PROCESS-RECORDS. PERFORM 2100-PREPARE-REPORT-RECORD PERFORM 2200-CALCULATE-INTEREST PERFORM 2300-UPDATE-BALANCE PERFORM 2400-WRITE-REPORT PERFORM 2500-READ-NEXT-RECORD. 2100-PREPARE-REPORT-RECORD. MOVE SPACES TO REPORT-RECORD MOVE CUSTOMER-NAME TO REPORT-NAME MOVE CUSTOMER-ID TO REPORT-ID. 2200-CALCULATE-INTEREST. EVALUATE ACCOUNT-TYPE WHEN 'S' COMPUTE INTEREST = BALANCE * 0.02 WHEN 'C' COMPUTE INTEREST = BALANCE * 0.01 WHEN OTHER MOVE ZERO TO INTEREST END-EVALUATE. 2300-UPDATE-BALANCE. ADD INTEREST TO BALANCE MOVE BALANCE TO REPORT-BALANCE MOVE INTEREST TO REPORT-INTEREST. 2400-WRITE-REPORT. WRITE REPORT-RECORD. 2500-READ-NEXT-RECORD. READ CUSTOMER-FILE AT END SET END-OF-FILE TO TRUE END-READ. 3000-TERMINATION. CLOSE CUSTOMER-FILE REPORT-FILE.

Exercise 3: Create a Coding Standards Document

Create a basic COBOL coding standards document for a team project. Your document should include:

  • Rules for naming different program elements (data items, paragraphs, files)
  • Formatting and indentation guidelines
  • Documentation requirements (comments, headers)
  • Module design principles
  • Examples of good and bad practices

Sample Solution Outline

COBOL Coding Standards for [Project Name]

  1. Naming Conventions

    • Data Items: Use descriptive names with hyphens (e.g., CUSTOMER-NAME)
    • Working Storage: Prefix with WS- (e.g., WS-COUNTER)
    • Files: End with -FILE (e.g., CUSTOMER-FILE)
    • Record Layouts: End with -RECORD (e.g., CUSTOMER-RECORD)
    • Paragraphs: Prefix with 4-digit number followed by descriptive name (e.g., 1000-INITIALIZATION)
  2. Formatting Guidelines

    • Indentation: 4 spaces for each level
    • Division headers: Column 8, followed by blank line
    • Section headers: Column 8, preceded by blank line
    • Paragraph headers: Column 8, preceded by blank line
    • Align PIC clauses and VALUES for data definitions
  3. Documentation Requirements

    • Program header with purpose, author, date, revision history
    • Section headers with purpose
    • Comments for complex calculations or business rules
    • Use 88-level items to document conditional values
  4. Module Design

    • Maximum paragraph size: 50 lines
    • Single responsibility for each paragraph
    • Use copybooks for common code
    • Top-down program structure
  5. Good/Bad Examples

    • Include examples of properly structured code vs. poorly structured code
    • Show before/after examples of improvements

Frequently Asked Questions