MainframeMaster

COBOL Tutorial

COBOL CONSTANT Clause

Master named constants and literal values with the CONSTANT clause. Learn how to improve code readability, maintainability, and reliability through proper constant definition and usage in your COBOL applications.

Overview

The CONSTANT clause in COBOL allows you to define named constants with fixed values that cannot be modified during program execution. This feature significantly improves code readability, maintainability, and reduces the risk of errors that can occur when using literal values scattered throughout your program.

Constants are particularly valuable for representing configuration values, business rules, mathematical constants, status codes, and other fixed values that your program uses repeatedly. By defining these values once as named constants, you create a single point of maintenance and make your code more self-documenting.

Modern COBOL programming emphasizes the use of constants as a best practice for creating robust, maintainable applications. Constants help eliminate "magic numbers" and make your code more professional and easier to understand by other developers.

Basic Syntax and Usage

Simple Constant Declaration

The basic syntax for declaring a constant involves using the CONSTANT clause with a VALUE specification. Here's the fundamental structure:

cobol
1
2
3
01 WS-MAX-RECORDS CONSTANT AS 1000. 01 WS-COMPANY-NAME CONSTANT AS "ACME Corporation". 01 WS-TAX-RATE CONSTANT AS 0.0825.

In this example, we define three constants: a numeric constant for maximum records, an alphanumeric constant for the company name, and a decimal constant for tax rate. The AS keyword specifies the constant value, which cannot be changed during program execution.

Typed Constants

You can specify the data type for constants using PICTURE clauses to ensure proper data representation and validation:

cobol
1
2
3
01 WS-ERROR-CODE PIC 9(4) CONSTANT AS 1001. 01 WS-SUCCESS-MSG PIC X(20) CONSTANT AS "OPERATION SUCCESSFUL". 01 WS-PI-VALUE PIC 9(1)V9(6) CONSTANT AS 3.141593.

These typed constants provide additional safety by ensuring the constant values conform to the specified data types. The compiler will validate that the constant value fits within the defined PICTURE specification.

Constants in Group Items

You can organize related constants into group items for better structure and logical grouping:

cobol
1
2
3
4
01 WS-SYSTEM-CONSTANTS. 05 WS-MAX-USERS CONSTANT AS 500. 05 WS-TIMEOUT-SECONDS CONSTANT AS 300. 05 WS-DEFAULT-LANG CONSTANT AS "EN".

Grouping constants logically makes your code more organized and easier to maintain. You can create groups for different functional areas like system limits, business rules, or configuration parameters.

Advanced Constant Techniques

Configuration Constants

Constants are excellent for defining configuration parameters that control program behavior. This approach makes it easy to modify program settings:

cobol
1
2
3
4
5
01 WS-CONFIG-CONSTANTS. 05 WS-DEBUG-MODE CONSTANT AS "Y". 05 WS-LOG-LEVEL CONSTANT AS 3. 05 WS-BATCH-SIZE CONSTANT AS 100. 05 WS-RETRY-ATTEMPTS CONSTANT AS 5.

These configuration constants can be referenced throughout your program to control debugging output, logging verbosity, batch processing sizes, and error recovery behavior. Changing these values in one place affects the entire program's behavior.

Business Rule Constants

Constants are perfect for encoding business rules and policies that may change over time but remain constant during program execution:

cobol
1
2
3
4
5
01 WS-BUSINESS-RULES. 05 WS-MIN-ORDER-AMT CONSTANT AS 25.00. 05 WS-FREE-SHIP-LIMIT CONSTANT AS 100.00. 05 WS-DISCOUNT-RATE CONSTANT AS 0.15. 05 WS-MAX-CREDIT-DAYS CONSTANT AS 30.

Business rule constants make your code self-documenting and easier to maintain when policies change. Instead of searching through code for literal values, you can update the business rules in one centralized location.

Status Code Constants

Using constants for status codes and return values improves code readability and reduces the chance of using incorrect values:

cobol
1
2
3
4
5
01 WS-STATUS-CODES. 05 WS-SUCCESS CONSTANT AS 0. 05 WS-ERROR-FILE-NOT-FOUND CONSTANT AS 1001. 05 WS-ERROR-INVALID-DATA CONSTANT AS 1002. 05 WS-ERROR-SYSTEM-FAILURE CONSTANT AS 9999.

Status code constants make your error handling logic much more readable and maintainable. Instead of using cryptic numeric codes, you can use meaningful names that clearly indicate the type of condition or error.

Tutorial: Building a Configuration-Driven Report System

Let's create a comprehensive reporting system that demonstrates the power of constants for configuration management and maintainable code. This tutorial will show you how to build a flexible system that can be easily modified through constant definitions.

Step 1: Define Report Configuration Constants

First, we'll establish constants that control the overall behavior and formatting of our report system:

cobol
1
2
3
4
5
6
WORKING-STORAGE SECTION. 01 WS-REPORT-CONFIG. 05 WS-PAGE-SIZE CONSTANT AS 60. 05 WS-LINE-SIZE CONSTANT AS 132. 05 WS-HEADER-LINES CONSTANT AS 5. 05 WS-FOOTER-LINES CONSTANT AS 3.

These constants define the basic page layout parameters. By using constants, we can easily modify the report format without searching through the entire program for hardcoded values. The page size, line width, and header/footer spacing are all centrally controlled.

Step 2: Define Formatting Constants

Next, we'll create constants for text formatting and display elements:

cobol
1
2
3
4
5
6
01 WS-FORMAT-CONSTANTS. 05 WS-TITLE-LINE CONSTANT AS "MONTHLY SALES REPORT". 05 WS-SEPARATOR CONSTANT AS "-". 05 WS-COLUMN-HEADERS CONSTANT AS "PRODUCT ID DESCRIPTION QUANTITY AMOUNT". 05 WS-DATE-FORMAT CONSTANT AS "MM/DD/YYYY".

Format constants ensure consistency throughout the report and make it easy to change titles, separators, and column headers. If the report requirements change, you can modify these constants rather than updating multiple locations in the code.

Step 3: Define Business Logic Constants

Now we'll create constants that control the business logic and calculations within our report:

cobol
1
2
3
4
5
01 WS-BUSINESS-CONSTANTS. 05 WS-HIGH-VOLUME-THRESHOLD CONSTANT AS 1000. 05 WS-COMMISSION-RATE CONSTANT AS 0.05. 05 WS-BONUS-MULTIPLIER CONSTANT AS 1.5. 05 WS-CURRENCY-SYMBOL CONSTANT AS "$".

Business logic constants encode the rules and calculations used in the report. These values define what constitutes high volume sales, commission rates, bonus calculations, and display formatting. Changes to business rules only require updating these constants.

Step 4: Implement Report Header Logic

Let's implement the report header generation using our defined constants:

cobol
1
2
3
4
5
6
7
8
9
10
11
PROCEDURE DIVISION. PRINT-REPORT-HEADER. WRITE REPORT-LINE FROM WS-TITLE-LINE MOVE ALL WS-SEPARATOR TO WS-SEPARATOR-LINE WRITE REPORT-LINE FROM WS-SEPARATOR-LINE WRITE REPORT-LINE FROM WS-COLUMN-HEADERS WRITE REPORT-LINE FROM WS-SEPARATOR-LINE ADD WS-HEADER-LINES TO WS-LINE-COUNT.

The header logic uses constants for the title, separator characters, and column headers. The line counting also uses the WS-HEADER-LINES constant to track page positioning. This makes the code self-documenting and easy to modify.

Step 5: Implement Data Processing with Constants

Finally, we'll process the report data using our business logic constants:

cobol
1
2
3
4
5
6
7
8
9
10
11
PROCESS-SALES-RECORD. IF WS-QUANTITY > WS-HIGH-VOLUME-THRESHOLD COMPUTE WS-COMMISSION = WS-AMOUNT * WS-COMMISSION-RATE * WS-BONUS-MULTIPLIER MOVE "HIGH VOLUME" TO WS-STATUS-FLAG ELSE COMPUTE WS-COMMISSION = WS-AMOUNT * WS-COMMISSION-RATE MOVE "STANDARD" TO WS-STATUS-FLAG END-IF PERFORM FORMAT-CURRENCY-DISPLAY.

The data processing logic uses constants to determine volume thresholds, calculate commissions, and apply bonus multipliers. This approach makes the business logic clear and easy to modify when requirements change.

Practical Exercises

Exercise 1: Employee Payroll Constants

Create a comprehensive set of constants for an employee payroll system:

cobol
1
2
3
4
5
6
* Define constants for: * - Tax rates (federal, state, local) * - Overtime multipliers * - Maximum deduction amounts * - Pay period information * - Benefits percentages

Solution Approach: Create logical groups of constants for different aspects of payroll processing. Include constants for tax calculations, overtime rules, deduction limits, and benefits processing. Ensure all business rules are represented as named constants rather than literal values.

Exercise 2: Inventory Management System

Design constants for an inventory management system with various business rules:

cobol
1
2
3
4
5
6
* Create constants for: * - Reorder points and quantities * - Discount tiers and percentages * - Storage location codes * - Product category limits * - Supplier rating thresholds

Solution Approach: Organize constants by functional area (purchasing, pricing, storage, quality). Use meaningful names that clearly indicate the purpose of each constant. Consider future maintenance needs when grouping related constants together.

Exercise 3: Financial Calculation Constants

Build a set of constants for financial calculations and compliance requirements:

cobol
1
2
3
4
5
6
* Define constants for: * - Interest rate calculations * - Regulatory compliance limits * - Currency conversion factors * - Risk assessment thresholds * - Audit trail requirements

Solution Approach: Focus on precision and accuracy for financial constants. Use appropriate decimal places for monetary calculations. Group constants by regulatory domain (banking, securities, insurance) and include documentation for compliance requirements.

Best Practices and Guidelines

Naming Conventions

  • Use descriptive names that clearly indicate the constant's purpose
  • Follow consistent naming patterns (e.g., WS-MAX-*, WS-DEFAULT-*)
  • Group related constants using common prefixes
  • Avoid abbreviations unless they are widely understood
  • Use ALL-CAPS for constant names to distinguish them from variables
  • Include units in names when applicable (e.g., WS-TIMEOUT-SECONDS)

Organization and Structure

  • Group constants logically by functional area or purpose
  • Place all constants at the beginning of WORKING-STORAGE
  • Use copybooks for constants shared across multiple programs
  • Document the purpose and usage of complex constants
  • Separate configuration constants from business rule constants
  • Consider using different level numbers for hierarchical organization

Maintenance and Documentation

  • Include comments explaining the business rationale for constant values
  • Document any dependencies between related constants
  • Maintain a change log for constant modifications
  • Review constants regularly to ensure they remain current
  • Use version control to track changes to constant definitions
  • Test thoroughly when modifying constant values

Performance Considerations

Constants can improve both performance and maintainability. The compiler can optimize constant references, potentially replacing them with literal values at compile time. This eliminates runtime lookups and can improve execution speed.

However, the primary benefit of constants is improved code quality and maintainability. The performance gains are secondary to the significant advantages in code readability, error reduction, and ease of maintenance that constants provide.

Interactive Quiz

Test Your CONSTANT Knowledge

Question 1:

What keyword is used to assign a value to a CONSTANT in COBOL?

Answer: AS. The AS keyword is used to assign a value to a CONSTANT in COBOL. For example: "01 WS-MAX-SIZE CONSTANT AS 100."

Question 2:

Can you modify the value of a CONSTANT during program execution?

Answer: No, constants are immutable. CONSTANT values are fixed at compilation time and cannot be modified during program execution. Any attempt to change them will result in a compilation error.

Question 3:

What is the primary benefit of using named constants instead of literal values?

Answer: Improved code readability and maintainability. Named constants make code self-documenting, reduce errors from typos, and provide a single point of maintenance when values need to change.

Frequently Asked Questions

Related Pages