Chapter 18 Exercises: COPY, REPLACE, and Copybook Management

Tier 1: Recall and Recognition (Exercises 1-8)

Exercise 1: COPY Statement Syntax

Fill in the blanks to write valid COPY statements:

a) Include the copybook named CUSTOMER-RECORD:

       ________ CUSTOMER-RECORD.

b) Include the copybook TRANS-REC from the library PRODCOPY:

       ________ TRANS-REC ________ PRODCOPY.

c) Include the copybook ACCT-LAYOUT and replace all occurrences of :TAG: with CHK:

       COPY ACCT-LAYOUT ________ ==:TAG:== ________ ==CHK==.

Answers: a) COPY b) COPY, OF (or IN) c) REPLACING, BY

Exercise 2: COPY Statement Rules

Answer True or False:

a) A COPY statement must end with a period. b) A COPY statement can appear inside a PERFORM loop. c) COPY is resolved at compile time, not at runtime. d) The COPY statement can bring in text for any COBOL division. e) You can place a COPY statement in the middle of a COBOL sentence (between two verbs).

Answers: a) True -- COPY is a compiler-directing statement and always ends with a period. b) False -- COPY is a compiler-directing statement resolved during compilation. It cannot be controlled by runtime logic like PERFORM. However, the copied text itself can appear inside a section that is PERFORMed. c) True -- the compiler resolves COPY statements during the text-processing phase, before syntax analysis. d) True -- copybook text can be placed in any division: IDENTIFICATION, ENVIRONMENT, DATA, or PROCEDURE. e) True -- a COPY statement can appear anywhere that the copied text would be valid, including mid-sentence. But this is unusual and can reduce readability.

Exercise 3: REPLACING Clause Mechanics

Given the following copybook named ACCT-FIELDS:

       05  :PREFIX:-ACCOUNT-NUM    PIC X(10).
       05  :PREFIX:-CUST-NAME      PIC X(30).
       05  :PREFIX:-BALANCE        PIC S9(9)V99.
       05  :PREFIX:-STATUS         PIC X(1).

Write the COPY statement with REPLACING to produce fields prefixed with CHK (for checking) and a second COPY with REPLACING to produce fields prefixed with SAV (for savings).

Answer:

       01  CHECKING-RECORD.
           COPY ACCT-FIELDS
               REPLACING ==:PREFIX:== BY ==CHK==.

       01  SAVINGS-RECORD.
           COPY ACCT-FIELDS
               REPLACING ==:PREFIX:== BY ==SAV==.

After compilation, the expanded source would contain:

       01  CHECKING-RECORD.
           05  CHK-ACCOUNT-NUM    PIC X(10).
           05  CHK-CUST-NAME      PIC X(30).
           05  CHK-BALANCE        PIC S9(9)V99.
           05  CHK-STATUS         PIC X(1).

       01  SAVINGS-RECORD.
           05  SAV-ACCOUNT-NUM    PIC X(10).
           05  SAV-CUST-NAME      PIC X(30).
           05  SAV-BALANCE        PIC S9(9)V99.
           05  SAV-STATUS         PIC X(1).

Exercise 4: REPLACE Directive

Explain the difference between COPY...REPLACING and the REPLACE directive. What does the following code do?

       REPLACE ==WS-TEMP== BY ==WS-TRANSACTION-AMOUNT==.
           ADD WS-TEMP TO WS-TOTAL.
           MOVE WS-TEMP TO WS-DISPLAY-FIELD.
       REPLACE OFF.
           MOVE WS-TEMP TO WS-ANOTHER-FIELD.

Answer: COPY...REPLACING operates only on the text brought in by a specific COPY statement. It is scoped to one COPY inclusion.

REPLACE operates on the entire source text (including both programmer-written code and text from COPY statements) from the point where REPLACE appears until REPLACE OFF or another REPLACE statement. It is a broader text substitution.

In the example: - After the first REPLACE, every occurrence of WS-TEMP is replaced by WS-TRANSACTION-AMOUNT in the source text. - The ADD and MOVE statements become: cobol ADD WS-TRANSACTION-AMOUNT TO WS-TOTAL. MOVE WS-TRANSACTION-AMOUNT TO WS-DISPLAY-FIELD. - After REPLACE OFF, substitution stops. The final MOVE remains: cobol MOVE WS-TEMP TO WS-ANOTHER-FIELD.

Exercise 5: Copybook Contents Identification

For each of the following, indicate whether it is a GOOD or BAD candidate for placing in a copybook, and explain why:

a) A customer record layout (01-level with subordinate fields) b) A paragraph containing business logic for interest calculation c) 88-level condition names for transaction type codes d) A WORKING-STORAGE field with a hardcoded file path e) An FD entry with its associated record description f) A SELECT clause for a standard file used by many programs

Answers: a) GOOD -- record layouts are the most common and most valuable copybook content. They ensure all programs use identical field names, sizes, and positions. b) BAD (debatable) -- procedure code in copybooks is technically valid but makes programs harder to read, debug, and maintain. Subprograms are a better choice for shared logic. c) GOOD -- condition names define the valid values for a field and should be consistent across all programs that use that field. d) BAD -- hardcoded paths are environment-specific. File paths should be handled via JCL DD statements or configuration files, not compiled into the program. e) GOOD -- FD entries paired with record descriptions ensure that all programs accessing a file use the same physical attributes and record layout. f) GOOD -- SELECT clauses ensure consistent file assignments and status handling across programs, though some shops prefer to leave SELECT clauses in individual programs for flexibility.

Exercise 6: Copybook Naming Conventions

A bank uses the following naming convention for copybooks: CBBXNNNN where: - CB = copybook prefix - B = business area (L=Lending, D=Deposits, G=General, P=Payments) - X = content type (R=Record, C=Constants, P=Parameters, S=Screen) - NNNN = sequence number

Write the copybook name for each of the following:

a) The loan account record layout (first copybook in Lending) b) The deposit transaction constants (third copybook in Deposits) c) The general error message parameters (second copybook in General) d) The payment screen layout (first copybook in Payments)

Answers: a) CBLR0001 (CB + L for Lending + R for Record + 0001) b) CBDC0003 (CB + D for Deposits + C for Constants + 0003) c) CBGP0002 (CB + G for General + P for Parameters + 0002) d) CBPS0001 (CB + P for Payments + S for Screen + 0001)

Exercise 7: Nested COPY

Explain what happens when a copybook itself contains a COPY statement. Given:

Copybook MAIN-LAYOUT:

       01  TRANSACTION-RECORD.
           05  TX-HEADER.
               COPY TX-HEADER-FIELDS.
           05  TX-BODY.
               COPY TX-BODY-FIELDS.
           05  TX-TRAILER.
               COPY TX-TRAILER-FIELDS.

How does the compiler process this when a program says COPY MAIN-LAYOUT?

Answer: The compiler resolves nested COPY statements recursively:

  1. The program's COPY MAIN-LAYOUT brings in the text of MAIN-LAYOUT.
  2. The compiler scans the brought-in text and finds three more COPY statements.
  3. COPY TX-HEADER-FIELDS is resolved, bringing in the header field definitions.
  4. COPY TX-BODY-FIELDS is resolved, bringing in the body field definitions.
  5. COPY TX-TRAILER-FIELDS is resolved, bringing in the trailer field definitions.
  6. If any of those copybooks contain further COPY statements, they are resolved as well (recursive descent).

The final expanded source contains the complete, fully resolved record layout with all fields from all nested copybooks. This modular approach allows each section of a complex record to be maintained independently.

Caution: Recursive (circular) COPY references (A copies B, B copies A) will cause an infinite loop during compilation. Compilers typically detect this and report an error.

Exercise 8: Compiler Listing

A programmer needs to debug a program that uses several copybooks. Where can they see the fully expanded source with all COPY statements resolved?

Answer: The compiler listing (also called the expanded source listing) shows the fully resolved source code. On IBM Enterprise COBOL, this is produced by the SOURCE or LIST compiler option. The listing shows:

  • Each line of the original source code
  • Lines brought in by COPY statements, typically marked with a C or + in the indicator column
  • The effects of REPLACING clauses applied to the copied text
  • Any REPLACE directive substitutions

On z/OS, the listing is written to the SYSPRINT DD in the compile JCL step. On GnuCOBOL, the -ftsymbols or --listing option produces a listing file.

The compiler listing is the definitive reference for debugging copybook-related issues because it shows exactly what the compiler sees after all text substitutions.


Tier 2: Comprehension and Application (Exercises 9-16)

Exercise 9: Predict the Expanded Source

Given the copybook BALANCE-FIELDS:

       05  :PFX:-CURRENT-BAL      PIC S9(11)V99 COMP-3.
       05  :PFX:-AVAILABLE-BAL    PIC S9(11)V99 COMP-3.
       05  :PFX:-HOLD-AMOUNT      PIC S9(11)V99 COMP-3.
       05  :PFX:-LAST-ACTIVITY    PIC X(8).
           88  :PFX:-DORMANT      VALUE SPACES.

And the following COPY statements:

       01  CHECKING-BALANCE.
           COPY BALANCE-FIELDS
               REPLACING ==:PFX:== BY ==CK==.

       01  SAVINGS-BALANCE.
           COPY BALANCE-FIELDS
               REPLACING ==:PFX:== BY ==SV==.

Write out the complete expanded source as the compiler would see it.

Answer:

       01  CHECKING-BALANCE.
           05  CK-CURRENT-BAL      PIC S9(11)V99 COMP-3.
           05  CK-AVAILABLE-BAL    PIC S9(11)V99 COMP-3.
           05  CK-HOLD-AMOUNT      PIC S9(11)V99 COMP-3.
           05  CK-LAST-ACTIVITY    PIC X(8).
               88  CK-DORMANT      VALUE SPACES.

       01  SAVINGS-BALANCE.
           05  SV-CURRENT-BAL      PIC S9(11)V99 COMP-3.
           05  SV-AVAILABLE-BAL    PIC S9(11)V99 COMP-3.
           05  SV-HOLD-AMOUNT      PIC S9(11)V99 COMP-3.
           05  SV-LAST-ACTIVITY    PIC X(8).
               88  SV-DORMANT      VALUE SPACES.

Note that the tag replacement works on every occurrence of :PFX: within the copied text, including inside the 88-level condition names. This produces correctly prefixed names for both record types.

Exercise 10: Write a Parameterized Copybook

Design a copybook named ACCT-IO-STATUS that can be used by any program to define file status handling fields and 88-level conditions. The copybook should use a tag :FILE: that the including program replaces with the specific file name.

The copybook should define: - A 2-character file status field - 88-level conditions for success, end-of-file, record not found, duplicate key, and permanent error - A display paragraph that shows the file name and status code

Answer: Copybook ACCT-IO-STATUS:

       05  :FILE:-STATUS           PIC XX VALUE '00'.
           88  :FILE:-SUCCESS      VALUE '00'.
           88  :FILE:-EOF          VALUE '10'.
           88  :FILE:-NOT-FOUND    VALUE '23'.
           88  :FILE:-DUPLICATE    VALUE '22'.
           88  :FILE:-PERM-ERROR   VALUE '30'.
           88  :FILE:-OK           VALUE '00' '02' '04'.

Usage in a program:

       01  WS-FILE-STATUS-FIELDS.
           COPY ACCT-IO-STATUS
               REPLACING ==:FILE:== BY ==MASTER==.
           COPY ACCT-IO-STATUS
               REPLACING ==:FILE:== BY ==TRANS==.
           COPY ACCT-IO-STATUS
               REPLACING ==:FILE:== BY ==REPORT==.

This produces:

       01  WS-FILE-STATUS-FIELDS.
           05  MASTER-STATUS       PIC XX VALUE '00'.
               88  MASTER-SUCCESS  VALUE '00'.
               88  MASTER-EOF      VALUE '10'.
               ...
           05  TRANS-STATUS        PIC XX VALUE '00'.
               88  TRANS-SUCCESS   VALUE '00'.
               ...
           05  REPORT-STATUS       PIC XX VALUE '00'.
               88  REPORT-SUCCESS  VALUE '00'.
               ...

Exercise 11: Multiple REPLACING Operands

Write a COPY statement that uses multiple REPLACING operands to customize a generic transaction record copybook. The copybook GENERIC-TRANS uses the tags :TYPE:, :AMT-SIZE:, and :DATE-FMT:. Replace: - :TYPE: with WIRE for wire transfer records - :AMT-SIZE: with 13 for the amount field precision - :DATE-FMT: with X(26) for an ISO timestamp format

Answer:

       01  WIRE-TRANSFER-RECORD.
           COPY GENERIC-TRANS
               REPLACING ==:TYPE:==     BY ==WIRE==
                         ==:AMT-SIZE:== BY ==13==
                         ==:DATE-FMT:== BY ==X(26)==.

Multiple REPLACING operands are separated by whitespace (no special delimiter). Each operand pair consists of ==old-text== BY ==new-text==. All replacements are applied to the copied text in the order specified. If the same text matches multiple patterns, the first match wins.

Exercise 12: COPY in Different Divisions

Show where and how you would use COPY statements in each of the four COBOL divisions. For each, provide a realistic example from a banking application.

Answer:

      * ENVIRONMENT DIVISION -- file control entries
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           COPY MASTER-FILE-SELECT.
           COPY TRANS-FILE-SELECT.
           COPY REPORT-FILE-SELECT.

      * DATA DIVISION -- record layouts and constants
       DATA DIVISION.
       FILE SECTION.
       FD  MASTER-FILE.
           COPY CUSTOMER-RECORD.

       WORKING-STORAGE SECTION.
       01  WS-CONSTANTS.
           COPY BANK-CONSTANTS.
       01  WS-ERROR-MESSAGES.
           COPY ERROR-MESSAGE-TABLE.
       01  WS-TRANSACTION-CODES.
           COPY TRANS-CODE-VALUES.

      * PROCEDURE DIVISION -- shared paragraphs (less common)
       PROCEDURE DIVISION.
           COPY STANDARD-ERROR-HANDLER.
           COPY AUDIT-LOGGING-PARA.

The DATA DIVISION (especially WORKING-STORAGE and FILE SECTION) is by far the most common location for COPY statements. ENVIRONMENT DIVISION copies are moderately common for standardizing file assignments. PROCEDURE DIVISION copies are the least common and most controversial -- most shops prefer subprograms over shared procedure code.

Exercise 13: Copybook Change Impact Analysis

A bank's CUSTOMER-RECORD copybook is used by 85 programs. A requirement comes in to add a new 15-character field (CUST-EMAIL-DOMAIN) to the record. The current record is exactly 200 bytes, and the FD entries in all 85 programs specify RECORD CONTAINS 200 CHARACTERS.

a) What must change in the copybook? b) What must change in all 85 programs? c) What is the risk if some programs are recompiled with the new copybook and others are not? d) How would you manage this change in a production environment?

Answer: a) Add the new field to the copybook and increase the record length. Either add the field at the end (safest) or repurpose existing FILLER space (if available).

b) All 85 programs must be recompiled with the updated copybook. If the record length changed from 200 to 215, all FD entries must be updated (or the FD should also be in a copybook to avoid this problem). All VSAM file definitions (IDCAMS DEFINE) must be updated if the record length changed.

c) This is the "Continental Savings Bank" scenario from the chapter opening. Programs compiled with the old 200-byte layout will read/write 200-byte records. Programs compiled with the new 215-byte layout will read/write 215-byte records. When both coexist, records written by new programs will be misread by old programs (fields will be shifted by 15 bytes), causing data corruption, ABENDs, or incorrect processing.

d) Management approach: 1. Coordinate the change through a formal change management process 2. Identify all 85 affected programs using a cross-reference tool 3. Update the copybook in the development library 4. Recompile ALL 85 programs in a controlled batch 5. Test thoroughly in a staging environment 6. Deploy all 85 recompiled programs simultaneously (not in waves) 7. Convert the VSAM file to the new record length (unload, redefine, reload) 8. Deploy during a planned maintenance window

Exercise 14: REPLACE for Bulk Renaming

A program was written with poor naming conventions. All fields start with A- when they should start with LOAN-. The program has 200 references to fields like A-ACCOUNT, A-BALANCE, A-RATE, etc.

Write a REPLACE directive that renames all these fields without modifying the copybook or editing each line individually.

Answer:

       REPLACE ==A-ACCOUNT== BY ==LOAN-ACCOUNT==
               ==A-BALANCE== BY ==LOAN-BALANCE==
               ==A-RATE==    BY ==LOAN-RATE==
               ==A-STATUS==  BY ==LOAN-STATUS==
               ==A-PAYMENT== BY ==LOAN-PAYMENT==
               ==A-TERM==    BY ==LOAN-TERM==.

      * All subsequent code uses the renamed fields
       ...
       (200+ lines of program code with A- prefixed names)
       ...

       REPLACE OFF.

Important caveat: REPLACE performs simple text matching, not semantic matching. If the program happens to contain unrelated text that matches (e.g., a literal string "A-RATE CHANGE"), it would also be replaced. The pseudo-text delimiters == == match on word boundaries, which mitigates this risk somewhat, but care is needed.

A better long-term solution is to fix the copybook and rename the fields properly, then recompile. REPLACE is a tactical fix for situations where you cannot modify the copybook.

Exercise 15: Copybook Library Management

A bank maintains copybooks in three libraries:

  • DEVLIB -- development copybooks (latest changes)
  • TESTLIB -- tested copybooks (approved for testing)
  • PRODLIB -- production copybooks (approved for production)

Explain how the compiler's copybook search order works and why it matters. Write JCL that ensures the compiler searches TESTLIB first, then PRODLIB, when compiling a test version of a program.

Answer: The compiler searches for copybooks in the libraries specified by the SYSLIB DD statement (or the LIB compiler option) in the order the libraries are concatenated. The first library containing a matching copybook name wins.

//COBOL   EXEC PGM=IGYCRCTL,PARM='LIB,SOURCE'
//SYSLIB   DD  DSN=BANK.TESTLIB,DISP=SHR
//         DD  DSN=BANK.PRODLIB,DISP=SHR
//SYSIN    DD  DSN=BANK.SOURCE(LOANPROC),DISP=SHR

In this JCL, the compiler searches TESTLIB first. If a copybook is found in TESTLIB, that version is used even if a different version exists in PRODLIB. If the copybook is not in TESTLIB, the compiler falls back to PRODLIB.

This matters because: - During development, DEVLIB should be first (to pick up latest changes) - During testing, TESTLIB should be first (to use the stable test versions) - During production compiles, PRODLIB should be first (or the only library) - If the wrong library order is used, a program might accidentally pick up a development version of a copybook in a production compile, introducing untested changes

Exercise 16: Copybook Versioning

Design a copybook versioning strategy for a bank that must maintain backward compatibility. The CUSTOMER-RECORD copybook has evolved through three versions:

  • V1: 100 bytes (original, 1995)
  • V2: 150 bytes (added email and phone fields, 2005)
  • V3: 200 bytes (added compliance fields, 2020)

Some legacy programs still use V1 and cannot be modified. How would you structure the copybook library to support all three versions simultaneously?

Answer: There are several strategies:

Strategy 1: Versioned copybook names

CUSTREC-V1.cpy  -- 100-byte layout
CUSTREC-V2.cpy  -- 150-byte layout
CUSTREC-V3.cpy  -- 200-byte layout (current)

Programs explicitly reference the version they need. New programs use V3. Legacy programs continue using V1 or V2. The drawback is that the copybook name differs, so you cannot transparently upgrade a program.

Strategy 2: Single copybook with FILLER padding

       01  CUSTOMER-RECORD.
           05  CR-CORE-FIELDS.     *> V1 fields (100 bytes)
               10  CR-CUST-ID      PIC X(10).
               10  CR-NAME         PIC X(30).
               ...
           05  CR-V2-FIELDS.       *> V2 additions (50 bytes)
               10  CR-EMAIL        PIC X(30).
               10  CR-PHONE        PIC X(15).
               10  FILLER          PIC X(5).
           05  CR-V3-FIELDS.       *> V3 additions (50 bytes)
               10  CR-COMPLIANCE   PIC X(20).
               10  CR-KYC-DATE     PIC X(8).
               10  FILLER          PIC X(22).

All programs use the same copybook. V1 programs that only reference CR-CORE-FIELDS continue to work (the extra fields are ignored). The physical record is always 200 bytes, with older programs reading past their needed data. This requires the file to be physically at V3 (200 bytes).

Strategy 3: Conditional compilation (if supported) Use compiler directives or REPLACE to conditionally include/exclude sections.

Strategy 2 is the most common in practice because it allows a single physical file format while supporting programs at different awareness levels.


Tier 3: Apply (Exercises 17-22)

Exercise 17: Debug This COPY Statement

The following code fails to compile. Identify and fix the error:

       01  LOAN-RECORD.
           COPY LOAN-FIELDS
               REPLACING ==:PFX:== BY ==LN==
           05  LN-EXTRA-FIELD      PIC X(20).

Answer: The COPY statement is missing its terminating period. The compiler interprets the 05-level line as part of the COPY statement's REPLACING clause, which causes a syntax error.

Fix: Add a period after the REPLACING clause:

       01  LOAN-RECORD.
           COPY LOAN-FIELDS
               REPLACING ==:PFX:== BY ==LN==.
           05  LN-EXTRA-FIELD      PIC X(20).

The period is mandatory on every COPY statement. It is one of the most common COPY-related compilation errors.

Exercise 18: Write a Complete Copybook Suite

Design and write a complete set of copybooks for a bank's loan processing system. Create the following copybooks:

LOAN-RECORD.cpy -- The loan account master record (80 bytes): - Loan Number (10), Borrower Name (30), Loan Type (2), Original Amount (9V99 COMP-3), Current Balance (9V99 COMP-3), Interest Rate (2V999 COMP-3), Origination Date (8), Status (1), Filler

LOAN-STATUS-CODES.cpy -- 88-level condition names for loan status

LOAN-FILE-CONTROL.cpy -- SELECT clause for the loan master file with a :PREFIX: tag for the file status field

Write a main program that includes all three copybooks and processes the loan file.

Hint: Use the :PREFIX: tag pattern in LOAN-RECORD and LOAN-FILE-CONTROL so that the same copybooks can be included multiple times (e.g., for old-master and new-master in an update program).

Exercise 19: Fix the Copybook Mismatch

Program A writes records using this copybook:

       01  CUST-REC.
           05  CR-ID               PIC X(10).
           05  CR-NAME             PIC X(30).
           05  CR-BALANCE          PIC S9(9)V99 COMP-3.
           05  CR-TYPE             PIC X(1).
           05  FILLER              PIC X(33).

Program B reads the same file using a local record definition (the programmer did not use the copybook):

       01  CUST-REC.
           05  CR-ID               PIC X(10).
           05  CR-NAME             PIC X(30).
           05  CR-BALANCE          PIC S9(9)V99.
           05  CR-TYPE             PIC X(1).
           05  FILLER              PIC X(29).

a) Identify the mismatch. b) What incorrect behavior will Program B exhibit? c) How would using a shared copybook have prevented this?

Answer: a) The mismatch is in CR-BALANCE. Program A defines it as COMP-3 (packed decimal), which occupies 6 bytes for PIC S9(9)V99. Program B defines it as display numeric (no COMP-3), which occupies 12 bytes for PIC S9(9)V99. The total record lengths also differ because FILLER was adjusted inconsistently.

b) Program B will misread the balance field because it expects 12 bytes of display numeric data but the file contains 6 bytes of packed decimal. The balance value will be garbled (unprintable characters interpreted as display digits). Additionally, CR-TYPE and everything after it will be at the wrong offset -- Program B reads CR-TYPE from byte 53, but Program A wrote it at byte 47. All subsequent fields are shifted.

c) If both programs used COPY CUST-RECORD, they would have identical field definitions. Any change to the record format would need to be made only in the copybook, and both programs would pick up the change on their next recompile. The copybook acts as a single source of truth.

Exercise 20: REPLACE for Testing

A program reads from a production file called PROD-MASTER. For testing purposes, you want to redirect it to a test file called TEST-MASTER without modifying the program source. Write REPLACE directives that change:

  1. The file name from PROD-MASTER to TEST-MASTER
  2. The ASSIGN clause from PRODMAST to TESTMAST
  3. A threshold constant from 10000.00 to 100.00 (lower threshold for testing)

Answer:

       REPLACE ==PROD-MASTER== BY ==TEST-MASTER==
               ==PRODMAST==    BY ==TESTMAST==
               ==10000.00==    BY ==100.00==.

Place this REPLACE directive at the very beginning of the program source (before the IDENTIFICATION DIVISION). It will affect all subsequent source text until REPLACE OFF is encountered or the program ends.

Important note: This approach works but has significant drawbacks: - It modifies the effective source code, making the compiled program different from what the source appears to show - It can cause unexpected replacements if the text patterns appear elsewhere - A better approach for file redirection is to use different JCL (changing DD statements) rather than REPLACE - For threshold changes, a configuration copybook or parameter file is more maintainable

REPLACE for testing is a legacy technique; modern shops prefer JCL-based or configuration-based test isolation.

Exercise 21: Nested Copybook Design

Design a hierarchical copybook structure for a bank's wire transfer message. The wire transfer record has three sections: header, payment details, and compliance information. Each section is complex enough to warrant its own copybook.

Create the following copybooks: - WIRE-MSG-LAYOUT (master copybook that includes the others) - WIRE-HEADER (message ID, sender, receiver, timestamp) - WIRE-PAYMENT (amount, currency, beneficiary account, remittance info) - WIRE-COMPLIANCE (sanctions screening result, AML flag, reporting threshold)

Use :TAG: replacement patterns so the entire structure can be included multiple times (e.g., for inbound and outbound messages).

Answer: See code/exercise-solutions.cob (EX21SOL)

Exercise 22: Cross-Reference Analysis

A bank's system has 150 COBOL programs and 45 copybooks. A critical bug has been found in the INTEREST-CALC copybook that contains PROCEDURE DIVISION code for calculating accrued interest. The bug causes a 1-cent rounding error on certain balance amounts.

a) Write a JCL job or utility command that would identify every program that includes INTEREST-CALC. b) How many programs might need recompilation? c) If the copybook contains PROCEDURE DIVISION code, why is this particularly risky to fix? d) Propose a safer architecture that would reduce the impact of such a fix.

Hint: On z/OS, ISRSUPC (ISPF Search-For utility) or a simple SORT/GREP of the source library can find COPY references. Cross-reference databases (like Endevor or ChangeMan) provide this information more reliably.


Tier 4: Analyze (Exercises 23-29)

Exercise 23: Copybook Design Patterns

A bank is designing a new account processing system. They need copybooks for: - Checking accounts (20 fields) - Savings accounts (18 fields, 15 in common with checking) - Money market accounts (22 fields, 16 in common with checking) - CD accounts (15 fields, 10 in common with checking)

Design two alternative copybook architectures: Architecture A: One copybook per account type (4 copybooks, with duplicated common fields) Architecture B: A base copybook with common fields + supplemental copybooks for type-specific fields

Analyze the trade-offs: maintenance burden, compilation efficiency, risk of divergence, flexibility for future account types.

Hint: Architecture B is generally superior, but it requires disciplined use of REPLACING or nested COPY to avoid naming conflicts.

Exercise 24: COPY Performance Impact

A senior developer claims that "too many COPY statements slow down compilation." Evaluate this claim:

a) Does COPY affect compilation time? If so, how? b) Does COPY affect runtime performance? c) Does COPY affect executable size? d) Is there a practical limit to the number of COPY statements in a program? e) What is the real performance concern with copybooks?

Hint: The real cost is not the COPY resolution itself (which is a simple text substitution) but the amount of data definition text that gets included.

Exercise 25: Debugging a REPLACING Failure

A programmer writes the following COPY with REPLACING, but the replacement does not take effect. The field names in the expanded source still show :TAG: instead of LOAN:

       COPY ACCOUNT-FIELDS
           REPLACING ==:TAG:==  BY  ==LOAN==.

The copybook ACCOUNT-FIELDS contains:

       05  : TAG :-BALANCE     PIC S9(9)V99.
       05  : TAG :-STATUS      PIC X(1).

Why does the replacement fail?

Hint: Look very carefully at the spacing in the copybook.

Exercise 26: Enterprise Copybook Governance

Design a copybook governance policy for a bank with 500 COBOL programs and 120 copybooks. Your policy should address:

a) Who is authorized to modify production copybooks? b) What is the review and approval process for copybook changes? c) How do you determine which programs are affected by a change? d) What is the mandatory testing process after a copybook change? e) How do you handle emergency copybook fixes (e.g., a production bug)? f) How do you retire obsolete copybooks?

Hint: Consider version control (Endevor, SCLM, Git), impact analysis tools, automated recompilation pipelines, and regression testing strategies.

Exercise 27: COPY vs. Subprogram Decision Matrix

For each of the following shared code scenarios, recommend whether to use a COPY statement (copybook) or a CALL statement (subprogram). Justify each recommendation.

a) A 50-field record layout shared by 30 programs b) A 200-line interest calculation algorithm shared by 12 programs c) A 5-line error message table with 88-level conditions d) A logging routine that writes to a shared audit file e) A date validation routine used by 100+ programs f) An FD entry with BLOCK CONTAINS and RECORDING MODE clauses

Hint: The general rule is: data definitions belong in copybooks, executable logic belongs in subprograms. But there are gray areas.

Exercise 28: REPLACE Scope Analysis

Analyze the following code and determine the final value of WS-RESULT after execution:

       REPLACE ==RATE== BY ==0.05==.

       WORKING-STORAGE SECTION.
       01  WS-PRINCIPAL     PIC 9(7)V99 VALUE 10000.00.
       01  WS-RATE           PIC 9V9(4)  VALUE RATE.
       01  WS-RESULT         PIC 9(7)V99 VALUE 0.

       REPLACE ==RATE== BY ==0.08==.

       PROCEDURE DIVISION.
           COMPUTE WS-RESULT = WS-PRINCIPAL * RATE
           DISPLAY WS-RESULT
           STOP RUN.

Hint: Remember that REPLACE operates at compile time during text processing. The second REPLACE overrides the first from that point forward. Trace the text substitution carefully, considering what the compiler actually sees.

Exercise 29: Copybook Migration Strategy

A bank is migrating from z/OS to a cloud-based GnuCOBOL environment. The z/OS copybooks are stored in PDS members (8-character names, no extensions). GnuCOBOL expects copybooks as regular files (with .cpy or .cbl extensions, case-sensitive names on Linux).

Design a migration strategy addressing: a) File naming conversion (8-char uppercase to meaningful names) b) How to handle the COPY statement syntax differences c) Copybook search path configuration d) Testing strategy to verify copied text is identical after migration

Hint: GnuCOBOL uses the -I (include path) option or the COB_COPY_DIR environment variable for copybook search paths. It also supports the COPY copybook-name syntax with automatic case folding and extension searching.


Tier 5: Create (Exercises 30-34)

Exercise 30: Complete Copybook-Based Banking System

Design and implement a complete set of copybooks for a small banking application, then write three programs that use them:

Copybooks (write the full content of each): 1. CUSTOMER-RECORD -- customer master layout 2. ACCOUNT-RECORD -- account master layout (with :TAG: for reuse) 3. TRANSACTION-RECORD -- daily transaction layout 4. STATUS-CODES -- file status handling with 88-levels 5. ERROR-MESSAGES -- standard error message table 6. BANK-CONSTANTS -- shared constants (bank name, rate thresholds, limits)

Programs (write complete programs using COPY): 1. ACCTLOAD -- loads accounts from a sequential file into an indexed file 2. TRANPROC -- processes daily transactions against account master 3. RPTGEN -- generates a daily account summary report

All three programs should use the shared copybooks. No record layout should be duplicated in program source.

Hint: This exercise tests whether your copybook design allows all three programs to compile and function correctly with the same set of copybooks. Pay special attention to the :TAG: pattern in ACCOUNT-RECORD, which ACCTLOAD uses once but TRANPROC uses twice (old-master and new-master).

Exercise 31: Copybook Refactoring Project

Take the following monolithic program (which contains all record definitions inline) and refactor it to use copybooks. The program processes loan payments against a loan master file:

       IDENTIFICATION DIVISION.
       PROGRAM-ID. LOANPMT.
       ...
       DATA DIVISION.
       FILE SECTION.
       FD  LOAN-MASTER.
       01  LM-RECORD.
           05  LM-LOAN-NUM        PIC X(10).
           05  LM-BORROWER        PIC X(30).
           05  LM-PRINCIPAL       PIC S9(9)V99 COMP-3.
           05  LM-RATE            PIC 9V9(4) COMP-3.
           05  LM-PAYMENT-AMT     PIC S9(7)V99 COMP-3.
           05  LM-NEXT-DUE        PIC 9(8).
           05  LM-STATUS          PIC X(1).
           05  FILLER             PIC X(19).

       FD  PAYMENT-FILE.
       01  PM-RECORD.
           05  PM-LOAN-NUM        PIC X(10).
           05  PM-AMOUNT          PIC S9(7)V99 COMP-3.
           05  PM-DATE            PIC 9(8).
           05  PM-SOURCE          PIC X(2).
           05  FILLER             PIC X(55).

       FD  EXCEPTION-FILE.
       01  EX-RECORD.
           05  EX-LOAN-NUM        PIC X(10).
           05  EX-AMOUNT          PIC S9(7)V99 COMP-3.
           05  EX-REASON          PIC X(30).
           05  EX-DATE            PIC 9(8).
           05  FILLER             PIC X(27).

Create copybooks for each record type and refactor the program to use COPY statements. Ensure the copybooks are usable by other programs in the loan system.

Exercise 32: Copybook Impact Analysis Tool

Design and write a COBOL program that performs copybook impact analysis. The program reads a source library (a sequential file where each record is a line of source code, with a program identifier in columns 73-80) and:

  1. Identifies all COPY statements in each program
  2. Extracts the copybook name from each COPY statement
  3. Builds a cross-reference: for each copybook, list all programs that use it
  4. For each program, list all copybooks it uses
  5. Produces a formatted report showing both views

This is a simplified version of what tools like Endevor's impact analysis provide.

Hint: Parse each source line looking for the word "COPY" followed by a copybook name (up to 30 characters). Handle the case where COPY is in column 12+ (standard COBOL) and ignore COPY that appears inside literals or comments.

Exercise 33: Copybook Generation Utility

Write a COBOL utility program that reads a metadata file describing a record layout and generates a COBOL copybook. The metadata file has one line per field:

FIELD-NAME,LEVEL,PIC-CLAUSE,VALUE-CLAUSE,USAGE-CLAUSE
LN-LOAN-NUM,05,X(10),,
LN-BORROWER,05,X(30),,
LN-PRINCIPAL,05,S9(9)V99,,COMP-3
LN-RATE,05,9V9(4),,COMP-3
LN-STATUS,05,X(1),,
LN-STATUS-ACTIVE,88,,VALUE 'A',
LN-STATUS-CLOSED,88,,VALUE 'C',

The program should generate a properly formatted COBOL copybook with correct indentation, alignment, and commenting.

Hint: This is a code generator -- a program that writes another program. Parse each metadata line using UNSTRING, format the COBOL field definition, and write it to the output file with proper column positioning.

Exercise 34: Enterprise Copybook Repository System

Design a complete copybook management system for a large bank. The system should include:

  1. Repository structure: How copybooks are organized, named, and stored
  2. Version control: How changes are tracked, how previous versions are preserved
  3. Impact analysis: How to determine which programs are affected by a copybook change
  4. Automated recompilation: How all affected programs are automatically recompiled and tested after a change
  5. Deployment pipeline: How copybook changes flow from development to test to production
  6. Audit trail: How every copybook change is logged for regulatory compliance

Write design documents for each component. Include JCL for the automated recompilation step and a COBOL program for the impact analysis component.

Hint: This is an architecture exercise. The repository could be a PDSE (Partitioned Data Set Extended) with version members, or a Git repository with z/OS integration. The automated recompilation pipeline would use JCL procedures with INCLUDE members or a build tool like IBM Dependency Based Build.