CodeAnt AI home pagelight logodark logo
  • Dashboard
  • Dashboard
  • Documentation
  • Demo Call with CEO
  • Blog
  • Slack
  • Get Started
    • CodeAnt AI
    • Setup
    • Control Center
    • Pull Request Review
    • IDE
    • Compliance
    • Anti-Patterns
      • Pyspark
      • Python
      • Java
      • C / CPP
      • C #
      • JavaScript
      • Jcl
      • Kotlin
      • Kubernetes
      • Abap
      • Apex
      • Azure Source Manager
      • Php
      • Pli
      • Plsql
      • Secrets
      • Swift
      • Terraform
      • Text
      • Tsql
      • Rpg
      • Ruby
      • Scala
      • Vb6
      • Vbnet
      • Xml
      • Flex
      • Go
      • Html
      • Docker
      • Css
      • Cobol
      • Common
    • Code Governance
    • Infrastructure Security Database
    • Application Security Database
    Anti-Patterns

    Cobol

    Shared coding conventions allow teams to collaborate efficiently. This rule checks that file-code names conform to a specified regular expression.

    INPUT-OUTPUT SECTION.
    FILE-CONTROL.
    
     SELECT Y27MVTS       ASSIGN  TO     S1        >Noncompliant; S1 doesn't match "FC-.*" pattern
                          FILE STATUS IS S1.
    

    You should avoid closing a CURSOR inside a PERFORM statement, because it could impact performance or lead to unexpected behavior if the cursor was not opened in the same loop.

    PERFORM UNTIL (NOT DA-OK)
       OR (Y00CIA-CD-RET-PGM = ZERO)
    EXEC SQL CLOSE C2
    END-EXEC
    END-PERFORM.
    

    To improve source code readability and reusability, SQL operations should be located in dedicated procedures (sections or paragraphs) and should not be mixed with other SQL requests.

    MAIN_PARAGRAPH.
    ...
    LOAD_SALARY.
    ...
    
    LOAD_SALARY.
    EXEC SQL CONNECT :UID IDENTIFIED BY :PASS END-EXEC.
    EXEC SQL USE tempdb END-EXEC.   *< Noncompliant
    EXEC SQL
    SELECT   SALARY  
        INTO  :HV-SALARY
      FROM EMPLOYEE
        WHERE EMPNAME = 'XXXXXXX'
    END-EXEC.
    EXIT.
    

    Aligning opening and ending words of statements is critical to keep the code readable, especially when blocks contain nested statements.

    For IF statements, this rule also checks the alignment of the ELSE word.

    IF SOME-STATUS = 1
    DISPLAY something
      END-IF.  *> Noncompliant
    

    TO BE TRANSLATED :

    L’objectif est de laisser la détermination taille des blocs physiques de fichier au niveau des JCL plutôt que de l’imposer par programme. Cela permet d’optimiser cette taille sans avoir à recompiler/livrer le programme

    Que doit-on contrôler?

    La présence de BLOC CONTAINS 0 RECORDS (ou BLOC 0, BLOC CONTAINS 0, etc)

    FD  MONFICHIER
    RECORD CONTAINS 10 CHARACTERS.
    01  ENR-LU         PIC X(10).
    

    To ensure future code portability, obsolete keywords should not be used. The following keywords were declared obsolete in the COBOL ANSI-85 standard and removed in the ISO/IEC 1989:2002 standard:

    • Paragraphs: `AUTHOR, INSTALLATION, DATE-WRITTEN, DATE-COMPILED, SECURITY

    • Clauses: DATA RECORD(S), LABEL RECORD(S), MEMORY SIZE, MULTIPLE FILE (TAPE), RERUN, VALUE OF, CODE SEGMENT-LIMIT

    • Statements: ALTER, ENTER, STOP literal, GO TO without an argument

    • Phrases: REVERSED phrase of the OPEN statement

    • Special registers: DEBUG-ITEM

    • Sections: Debugging sections

    • Declarative: USE FOR DEBUGGING

    The following keywords were declared obsolete in the ISO/IEC 1989:2002 standard:

    • Phrase: DEBUGGING MODE

    • Clause: PADDING CHARACTER`

    IDENTIFICATION DIVISION.
    PROGRAM-ID.  AcceptAndDisplay.
    AUTHOR.  Michael Coughlan.  *> Noncompliant
    

    Changing procedural copybooks may potentially cause issues where many programs are pulled into a package for recompile and then a potential for bind issues during turnover. Having to edit procedural copybooks frequently causes delays in program maintenance as developers have to wait for another developer to complete their work. This also causes double work when programs get out of sync and a recent change could potentially be lost in a program.

    PROCEDURE DIVISION.
    ...
    COPY MY_COPYBOOK.        <- Noncompliant
    ...
    

    GO TO should not be used to transfer control outside the current module, because any implied EXIT points will then be ignored. A module is either a section, a paragraph, or a set of paragraphs called with the PERFORM … THRU … statement.

    PERFORM PARAGRAPH1 THRU PARAGRAPH3.     > code contained between PARAGRAPH1 and PARAGRAPH3 is now considered as a module
         EXIT PROGRAM.
    
        PARAGRAPH1.
         MOVE A TO B.
         IF SOMETHING
           GO TO PARAGRAPH3     >OK
         END-IF.
         IF SOMETHING-ELSE 
           GO TO PARAGRAPH4     >NOK as we leave the module called with "PERFORM PARGRAPH1 THRU PARAGRAPH3" statement
         END-IF.
    
        PARAGRAPH2.
         MOVE A TO B.
    
        PARAGRAPH3.
         EXIT.
    
        PARAGRAPH4.
    

    The ACCEPT statement causes data entered at the console or provided by the operating system to be made available to the program in a specific data element, without any validation or sanitization.

    Thus, if this data is accepted in a particular format and used by other procedures, the system is vulnerable to attack or malfunction.

    IDENTIFICATION DIVISION.
    PROGRAM-ID. EXAMPLE.
    
    DATA DIVISION.
    WORKING-STORAGE SECTION.
    01 WS-NUMERIC PIC X VALUE 'N'.
    01 USER-INPUT PIC X(4).
    
    PROCEDURE DIVISION.
    EXAMPLE-PROCEDURE.
    MOVE 'N' TO WS-NUMERIC.
    PERFORM UNTIL WS-NUMERIC = 'Y'
        DISPLAY 'ENTER YOUR 4 DIGIT RECORD NUMBER: ' NO ADVANCING
        ACCEPT USER-INPUT FROM CONSOLE *> Noncompliant
        MOVE 'Y' TO WS-NUMERIC
    END-PERFORM
    STOP RUN.
    

    You should avoid opening a cursor inside a PERFORM statement because doing so could impact performance, or lead to unexpected behavior if the the closing of the cursor is not defined in the same loop.

    PERFORM UNTIL (NOT DA-OK) OR (Y00CIA-CD-RET-PGM = ZERO)
    EXEC SQL OPEN C2
    END-EXEC
    END-PERFORM.
    

    According to the IBM documentation,

    To aid in migrations to IBM Enterprise COBOL 5.x, this rule raises an issue when UPPER-CASE, LOWER-CASE, or NATIONAL-OF` is used.

    MOVE FUNCTION UPPER-CASE(FIRST-NAME) to FIRST-NAME2.  *> Noncompliant    
        MOVE FUNCTION LOWER-CASE(FIRST-NAME) to FIRST-NAME2.  *> Noncompliant
    

    The DISPLAY statement outputs data to standard out or some other destination and could reveal sensitive information. Therefore, it should be avoided.

    DISPLAY "hello world"  *> Noncompliant
    

    The number of distinct data items used in a condition (IF, EVALUATE, …​) should not exceed a defined threshold.

    IF WS-FOO(1) = 1 OR *> 1st data item
    WS-FOO(2) = 2 OR
    WS-FOO(3) = 3 OR
    WS-BAR = 4 OR *> 2nd data item
    WS-BAZ = 5 OR *> 3rd data item
    WS-QUX = 42 *> Noncompliant; 4th data item
    END-IF.
    

    The use of an array structure is useless when the array only has one element. Using an array structure anyway can impact performance and decrease the readability of the source code.

    03 WS-LIBELLE OCCURS 1.
    

    Level 77 identifies data items that are not subdivisions of other items, and that have no subdivisions. They are atomic by declaration. To make future subdivision possible, level 01 should be used instead of level 77.

    77 CAR            PIC 999.
    

    Every section should be commented to explain its goal and how it works. This comment can be placed either just before or just after the section label.

    UNCOMMENTED-SECTION SECTION.
    

    Call stacks containing lot of PERFORM statements is a key ingredient for making what’s known as “Spaghetti code”.

    Such code is hard to read, refactor and therefore maintain.

    This rule supports both sections and paragraphs.

    PERFORM FIRST.
    
    FIRST.
    PERFORM SECOND.
    
    SECOND.
    PERFORM THIRD.
    
    THIRD.
    PERFORM FOURTH.  *> Noncompliant
    
    FOURTH.
    DISPLAY something.
    

    CAST(… AS CHAR/VARCHAR) can be a source of incompatibilities between database versions: the behavior of CAST may not be the same depending on the version of the database system. Such incompatibilities can cause unexpected output from applications that CAST decimal data to CHAR or VARCHAR, it’s therefore best to avoid using CAST(… AS CHAR/VARCHAR).

    DELETE product
    WHERE CAST(status_code AS CHAR(2)) = '42' -- Noncompliant
    

    You should avoid declaring a cursor inside a PERFORM statement because doing so could impact performance. It could also lead to unexpected behavior if the opening and closing of the cursor are not defined in the same loop.

    PERFORM UNTIL (NOT DA-OK) OR (Y00CIA-CD-RET-PGM = ZERO)
    EXEC SQL  DECLARE C2 CURSOR FOR
      SELECT DEPTNO, DEPTNAME, MGRNO FROM DEPARTMENT WHERE ADMRDEPT = 'A00'
    END-EXEC
    END-PERFORM.
    

    Most COBOL environments do not support recursive PERFORM calls, since they can cause unpredictable results. This rule raises an issue when recursive PERFORM calls are used.

    PARAGRAPH1.
    PERFORM PARAGRAPH2.
    
    PARAGRAPH2.
    PERFORM PARAGRAPH3.
    
    PARAGRAPH3.
    PERFORM PARAGRAPH1.
    

    When a `SELECT returns null from a nullable column, the relevant host variable isn’t updated; it simply retains its previous value. The only way you’ll ever know the column value was null is to check the relevant null indicator included in the SELECT for a negative (null) value.

    This rule raises an issue when a SELECT omits a null` indicator for a nullable column.

    Note that this rule raises issues only when a database catalog is provided during the SonarQube analysis.

    EXEC SQL
    SELECT 
    PROD_ID, 
    NAME
    INTO  
    :P-ID,
    :P-NAME                 -- Noncompliant; No null indicator
    FROM PRODUCT
    END-EXEC
    

    The use of DUMP and DUMP TRANSACTION, while potentially useful during development and debugging, could expose system information to attackers and should not be used in production.

    EXEC CICS DUMP TRANSACTION  *> Noncompliant
    DUMPCODE('dumpfile')
    FROM (area-to-dump)
    LENGTH (data-to-dump)
    END-EXEC.
    

    When the size of a variable-length table is DEPENDING ON a non-BINARY/COMP variable, use of that table is inefficient because a conversion must be done every time the table is used.

    01 VARS
    05 TABLE_SIZE   PIC 9(4).
    05 MY_TABLE OCCURS 1 TO 10
                        DEPENDING ON TABLE_SIZE  *> Noncompliant; TABLE-SIZE isn't BINARY or COMP
                        PIC X(10).
    

    When error conditions occur, it is usually a bad idea to simply ignore them. Instead, it is better to handle them properly, or at least to log them.

    EXEC CICS
    ...
    INGNORE CONDITION ERROR *> Noncompliant
    END-EXEC.
    

    Shared coding conventions allow teams to collaborate efficiently. This rule checks that data item levels are incremented according to the configured values.

    Using the default configuration:

    01 StudentDetails.
    05 StudentName. 
      12 FirstName     Pic x(10).   *> Noncompliant, level 10 is expected
      10 MiddleInitial Pic x.
      10 Surname       Pic x(15).  
    03 StudentId        Pic 9(7).      *> Noncompliant, only 05 level is expected
                 *> We should not mix two types of incrementation in the same data structure
    ...
    01  Customer-Record.
    03  Customer-Name.
        10 Last-Name         Pic x(17).   *> Noncompliant, level 05 is expected
        05 Filler            Pic x.
        05 Initials          Pic xx.
    03  Part-Order.
        05 Part-Name         Pic x(15).
        05 Part-Color        Pic x(10).
            10 Part-Color-Code        Pic x.   *> Noncompliant, level 07 is expected
    

    There’s no point in including the default value of a column in an insert statement. It simply clutters the code to no additional benefit.

    Note that this rule raises issues only when a database catalog is provided during the SonarQube analysis.

    EXEC SQL
    INSERT INTO PRODUCT
    (
    NAME,
    INV_COUNT  -- Noncompliant
    )
    VALUES
    (
    :PROD-NAME,
    0  -- this is the default value
    )
    END-EXEC
    

    Merging collapsible IF statements increases the code’s readability.

    Code like

    IF CONDITION1 THEN
         IF CONDITION2 THEN              *> Noncompliant
           ...
         END-IF
       END-IF.
    

    Initializing a data item with a value of the wrong type will lead to runtime errors. The rule checks that numeric data items are not initialized with alphanumeric/alphabetic values and that alphanumeric /alphabetic data items are not initialized with numeric values.

    WORKING-STORAGE SECTION.
         EJECT
       01  TAB-POS.
           02  FILLER  PIC A(14) VALUE 0.  *> Noncompliant
           02  FILLER  PIC 9(14) VALUE 'ASDFJKL;QWERTY'.  *> Noncompliant
    
       01 MYGROUP PIC 9(1).
          88 X VALUE 1,2.
          88 Y VALUE 3, "BLUE".  *> Noncompliant; BLUE is alphanumeric
    

    Pour des traitements effectuant des COMMITs réguliers et afin de conserver la position du CURSOR lors de lecture ou de mises à jour, il est impératif que les DECLARE CURSOR soient codés avec l’option WITH HOLD

    EXEC SQL DECLARE CLEC_0 CURSOR WITH HOLD
                    	FOR SELECT	C_BQ
                              		,C_CARNT_ORDREB
                              		,N_REF_ORDREB…..
          FROM       S1ORDCOU
          WHERE
    ( C_BQ               >=  :TORD-C-BQ               ) AND NOT
    ( C_BQ                =  :TORD-C-BQ                 AND…..
    ORDER BY C_BQ,C_CARNT_ORDREB,N_REF_ORDREB
    FOR FETCH ONLY
    END-EXEC.
    

    After calling CICS commands with the RESP or NOHANDLE options, the return code should be tested.

    EXEC CICS DELETEQ TS        *> Noncompliant; WS-STATUS should have been tested before the MOVE
    QNAME(WS-TS5FTARF-NAME)
    RESP(WS-STATUS)        
    END-EXEC.                   
    MOVE WS-EIBTASKN (4:4) TO WS-TS5FTAR1-NAME-TSKID.
    

    88-level variables, also known as “condition name” variables, each have a name, a value or set of values, and a “parent” variable. Those parent variables are called “conditional variables”.

    Each 88-level variable can be seen as a short-cut conditional for testing the value of the parent: IF MY-88 will intrinsically return true if the parent value matches MY-88’s value, and false if it does not.

    Thus, testing a conditional variable against a literal value is redundant and confusing. Just use the 88-levels instead.

    01 COLOR PIC X
    88 YELLOW VALUE 'Y'
    88 GREEN VALUE 'G'
    88 RED VALUE 'R'
    ...
    IF COLOR = 'G' *> Noncompliant
    ...
    END-IF
    

    Every paragraph should be commented to explain its goal and how it works. This comment can be placed either just before or just after the paragraph label. Moreover paragraphs used to close a module can be left uncommented.

    PROCEDURE DIVISION.
    
    PARAGRAPH1.           *> Noncompliant
    ...
    
    *-------
    PARAGRAPH2.           *> Noncompliant; the comment is empty
    ...
    
      PERFORM P1 THRU P2.
    ...
    
    *Some comments                                  *> Compliant
    P1.
      ....
    
    P2.                                         *> No violation as the this P2 paragraph close a module
       MOVE A TO B.
       ...
       EXIT.
    

    When using some transaction managers like IBM IMS, each COBOL program is in fact considered a sub-program by the transaction manager. The GOBACK statement returns control to the transaction manager, but using STOP RUN might cause unpredictable results or abnormal termination.

    STOP RUN
    

    This rule allows banning certain statements.

    DISPLAY "Cancelling action".
    CANCEL PROGRAM1. *> Noncompliant
    

    Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of arithmetic operators, having the same value on both sides of an operator yields predictable results, and should be simplified.

    * always true
    IF X = X
    PERFORM SECTION1.
    END-IF.
    
    * always false
    IF X <> X
    PERFORM SECTION2.
    END-IF.
    
    * if the first one is true, the second one is too
    IF X = Y AND X = Y
    PERFORM SECTION3.
    END-IF.
    
    * if the first one is true, the second one is too
    IF X = Y OR X = Y
    PERFORM SECTION4.
    END-IF.
    
    * always 1
    COMPUTE X = Y / Y.
    
    * always 0
    COMPUTE X = Y - Y.
    

    A EVALUATE and a chain of IF/ELSE IF statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

    Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it’s simply dead code and at worst, it’s a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior.

    EVALUATE X
    WHEN 1
       ...
    WHEN 5
       ...
    WHEN 3
       ...
    WHEN 1     *> Noncompliant
       ...
    END-EVALUATE.
    
    IF X = 1
    ...
    ELSE
    IF X = 2
    ...
    ELSE
    IF X = 1    *> Noncompliant
      ...
    END-IF
    END-IF
    END-IF.
    

    Debug statements (ones with ‘D’ or ‘d’ in the indicator area) should not be executed in production, but the WITH DEBUGGING MODE clause activates all debug lines, which could expose sensitive information to attackers. Therefore the WITH DEBUGGING MODE clause should be removed.

    SOURCE-COMPUTER. IBM-370 WITH DEBUGGING MODE.
    

    This rule is a more precise version of S1308 preventing the use of GO TO. The flow of a program is already complicated to understand with simple GO TOs. It’s even worse when a GO TO is executed conditionally like this is the case with GO TO DEPENDING ON.

    PROCEDURE DIVISION.
    ...
    GO TO PARAGRAPH-10
         PARAGRAPH-20
         PARAGRAPH-30
    DEPENDING ON WS-PARA-NUMBER *> Noncompliant
    ...
    

    The rules of operator precedence are complicated and can lead to errors. For this reason, parentheses should be used for clarification in complex statements.

    This rule raises an issue when more than the allowed number of non-like operators are used in a statement without parentheses to make execution order explicit.

    COMPUTE WSRESULT = WS1 + 5 * WS2 - WS3**2 END-COMPUTE  *> Noncompliant
    COMPUTE WSRESULT2 = WS1 + 5 + WS2 + WS3 + WS4 END-COMPUTE
    

    Because statically-called programs must be relinked before they reflect changes in the code, it makes sense to prefer dynamic calls instead. Further, since statically-called programs are included in the caller’s load module, those modules could require more main storage than if the calls were dynamic, and the called programs could reside in memory multiple times - one for each caller.

    While static calls are faster, their other disadvantages make dynamic calls the preferred method. Thus, this rule raises an issue when the program to CALL is hard-coded, rather than specified in a variable.

    CALL 'MYPRGM01' USING PARAM1.  *> Noncompliant
    

    88-level variables, also known as “condition name” variables, represent possible values of the “conditional variables” they’re tied to. Because a condition name can be used to test the value of its conditional variable without any other contextual references to the conditional variable being tested, it makes the code easier to understand if the name of the 88-level variable references its conditional variable.

    This rule raises an issue when the name of an 88-level variable does not start with the first characters of the name of its conditional variable.

    01 COLOR PIC X.
    88 YELLOW VALUE 'Y'. *> Noncompliant
    88 GREEN VALUE 'G'. *> Noncompliant
    88 RED VALUE 'R'. *> Noncompliant
    
    * ...
    IF GREEN  *> What does this mean?
    * ...
    END-IF
    

    Even though closing an open file isn’t always mandatory (for instance when stopping the execution of a COBOL program with the STOP RUN statement), it’s good coding practice to always explicitly close any open files. This rule checks that for every OPEN statement there is a corresponding CLOSE statement somewhere in the program.

    OPEN INPUT my-file
    

    Paragraphs, sections and statements must be correctly indented for better code readability.

    IDENTIFICATION DIVISION.
       PROGRAM-ID. foo.
    
       PROCEDURE DIVISION.
           IF "foo" = "bar" THEN
           DISPLAY "foo = bar!"      *> Noncompliant
           ELSE
           DISPLAY "foo <> bar!".      *> Noncompliant
       END PROGRAM foo.
    

    Explicitly defining a cursor as read-only can improve performance by avoiding table locking. This allows other SQL requests to execute in parallel. Therefore when a cursor will only be used to read data, without modifying anything, the `FOR READ ONLY clause or its synonyn, FOR FETCH ONLY, should be used.

    Conversely when a cursor will modify data, that too should be specified using the FOR UPDATE clause.

    In short, it’s better to always explicitly define the purpose of the cursor with help of the FOR READ ONLY, FOR FETCH ONLY or FOR UPDATE` clauses.

    EXEC SQL DECLARE CMAJ_0A CURSOR
    FOR SELECT C_BQ
    FROM       S1ORDCOU
    WHERE C_BQ = :TORD-C-BQ
    END-EXEC
    

    Using FETCH FIRST n ROWS ONLY in a SELECT without ordering the results from which the “n first” results are chosen will return a seemingly random set of rows, and is surely a mistake.

    SELECT fname, lname, city
    FROM people
    WHERE city IS NOT NULL
    FETCH FIRST 10 ROWS ONLY; -- Noncompliant selects 10 random rows
    

    Using a scalar function or an arithmetic expression in a WHERE condition can prevent the database from using indexes on the relevant column(s), and could therefore lead to performance issues.

    SELECT * FROM MY_TABE WHERE C2 = C3 + :HostVar1  -- Noncompliant
    
    SELECT * FROM MY_TABLE WHERE YEAR(BIRTHDATE) > 2000  -- Noncompliant
    

    There should not be any statements after EXIT PROGRAM. Such statements cannot be reached, and are therefore dead code. Dead code makes a program more complex and therefore more difficult to maintain.

    PROCEDURE DIVISION.
    PARAGRAPH1.
      MOVE A TO B.
      EXIT PROGRAM.   >NOK as the following "MOVE B TO C" statement will never be called
      MOVE B TO C.
    

    OS/VS COBOL accepted the NOTE statement, but IBM Enterprise COBOL does not. Therefore all NOTE statements should be replaced by standard comment lines.

    IDENTIFICATION DIVISION.
       PROGRAM-ID. foo.
    
       PROCEDURE DIVISION.
      * Non-Compliant
         NOTE This is a comment.
    
      * This is a compliant comment.
       END PROGRAM foo.
    

    Shared coding conventions allow teams to collaborate efficiently. This rule checks that logical file names conform to a provided regular expression.

    INPUT-OUTPUT SECTION.
    FILE-CONTROL.
    
     SELECT Y27MVTS       ASSIGN  TO     S1       >Noncompliant
                          FILE STATUS IS FS-S1.
    

    Using recursion with paragraphs is not a problem in itself but it potentially exposes the software to endless loop. This is the case when there is no condition to end the recursion or when this condition is always false.

    This rule raises an issue when a paragraph contains a PERFORM to itself to warn the developer that there is a risk of endless loop. This rule can also be used to fully prevent recursion to be used.

    PROCEDURE DIVISION.
    ...
    PERFORM READ-RELATED-REC-PARA
    ...
    READ-RELATED-REC-PARA.
    ...
    CALL MY-MODULE
    IF MORE-RECS
      PERFORM READ-RELATED-REC-PARA
    ...
    

    TODO

    PERFORM UNTIL FIN-RGL0
     PERFORM DEBUT-RGL0
     PERFORM UNTIL FIN-RGL1
     PERFORM DEBUT-RGL1
          PERFORM UNTIL FIN-RGL2
           PERFORM DEBUT-RGL2
           PERFORM ALIM-RGL2
           PERFORM FIN-RGL2
     END-PERFORM
     PERFORM FIN-RGL1
    END-PERFORM
     PERFORM FIN-RGL0
    END-PERFORM
    

    Having several levels of nested SQL SELECT statements makes the code difficult to read and should therefore be avoided.

    *> Non-Compliant
    EXEC SQL
    SELECT * FROM my_table1 WHERE
    my_column1 IN
      (SELECT my_column2 FROM my_table2
        WHERE my_column3 IN
          (SELECT my_column4 FROM my_table3))
    END-EXEC.
    

    Nested control flow statements IF, PERFORM, EVALUATE and others are often key ingredients in creating what’s known as “Spaghetti code”. This code smell can make your program difficult to understand and maintain.

    When numerous control structures are placed inside one another, the code becomes a tangled, complex web. This significantly reduces the code’s readability and maintainability, and it also complicates the testing process.

    IF A = 1
    PERFORM 
        MOVE A TO B
        PERFORM
            IF B = 1 *> Noncompliant
              MOVE "HI" TO S1  
            END-IF
        END-PERFORM
    END-PERFORM
    END-IF.
    

    The number of columns in a FETCH statement should match the number actually selected in the relevant cursor. Use more columns in the FETCH than the cursor, and you’ve got a data problem, because the variables you expect to be updated by the cursor are never actually touched, and neither are their null indicators. Instead, they retain whatever value they had before the fetch. Meaning you’re operating with bad data.

    EXEC SQL
        DECLARE C-SQL-CURSOR CURSOR
          SELECT COLUMN1
                ,COLUMN2
                ,COLUMN3
            FROM TBLWTABLE
          WITH UR
      END-EXEC.
    
      …
    
      EXEC SQL
        FETCH C-SQL-CURSOR
        INTO  :H-COLUMN1 :H-COLUMN1-IND  -- Noncompliant
             ,:H-COLUMN2 :H-COLUMN2-IND
             ,:H-COLUMN3 :H-COLUMN3-IND
             ,:H-COLUMN4 :H-COLUMN4-IND  -- Not selected
             ,:H-COLUMN5 :H-COLUMN5-IND  -- Not selected
    

    The storage of a packed numeric field is most efficient when you code an odd number of digits in the PICTURE description, so that the leftmost byte is fully used. Packed-decimal items are handled as fixed-point numbers for arithmetic purposes.

    01 VAL PIC 9(6) COMP-3.
    

    There can’t be any good reason to do a full table scan on large database tables due to the cost of such operation and the scalability issue that might raise. This rule raises an issue when a SELECT statement doesn’t use at least one indexed column in its WHERE clause.

    Note That this rule raises issues only when a database catalog is provided during the SonarQube analysis.

    SELECT * FROM USERS WHERE NAME = :name  -- non compliant when NAME column is not indexed
    

    OS/VS COBOL accepted the ON statement, but IBM Enterprise COBOL does not accept it anymore. The ON statement allows the selective execution of statements it contains. Similar functions are provided in Enterprise COBOL by EVALUATE and IF

    IDENTIFICATION DIVISION.
       PROGRAM-ID. foo.
    
       PROCEDURE DIVISION.
      * Non-Compliant
         ON 1
           DISPLAY 'First time'
         ELSE
           DISPLAY 'Other times'.
       END PROGRAM foo.
    

    OCCURS DEPENDING ON clauses are complicated to use correctly and do not provide any benefits with regard to memory consumption. It is best to avoid them.

    01  MYTABLEACCOUNT PIC S9(4) BINARY.
    01  MYTABLE.
    05  MYITEM OCCURS 1 to 1000 DEPENDING ON MYTABLEACCOUNT.
        10  MYFIELD1 PIC X(8).
        10  MYFIELD2 PIC S9(4) BINARY.
    

    L’instruction INSERT/SELECT correspond à des mises à jour de masse sans possibilité de prendre des commits intermédiaires. Ce qui est très dommageable en terme d’accès concurrents sur des environnements 24/24 7/7.

    EXEC SQL INSERT INTO TESTPROJ (PROJNO, PROJNAME, DEPTNO)
    	              SELECT PROJNO, PROJNAME, DEPTNO
    	              FROM S1TESTPR
    	              WHERE DEPTNO LIKE ‘B%’ END-EXEC.
    

    Some COBOL compilers such as IBM one will assume that the minimum value of `OCCURS DEPENDING ON is 1 but nothing is enforcing that and this behaviour can change or be different when using another compiler.

    Setting the minimum value of OCCURS DEPENDING ON` makes the code more readable, and less dependent on compiler.

    01 MY-TABLE-COUNT PIC S9(4) BINARY.
    01 MY-TABLE.
    03 MY-ITEM OCCURS 500 TIMES          *> Noncompliant
       DEPENDING ON MY-TABLE-COUNT.
      05 MY-FIELD-01 PIC X(08).
      05 MY-FIELD-02 PIC 9(05).
    

    Defining a subprogram to be called at runtime is possible but ill-advised. This extremely powerful feature can quite easily be misused, and even when used correctly, it highly increases the overall complexity of the program, and makes it impossible before runtime to know exactly what will be executed. Therefore defining the subprogram to be called at runtime is a feature that should be avoided.

    MOVE SOMETHING TO MY_SUBPROG.
    ...
    CALL MY_SUBPROG.
    

    Using a data value clause in the LINKAGE SECTION can lead to unexpected behavior at runtime.

    LINKAGE SECTION.
    
    01 CAR-ID PIC X(20) VALUE IS "VOLVO".   *> Noncompliant
    
    01  EMP-TYPE     PIC X.
    88   FULL-TIME-EMPLOYEE VALUE "F".   *> Compliant; this is a condition name
    88   PART-TIME-EMPLOYEE VALUE "P".
    
    01 TRAIN-ID PIC X(20)
    

    The `LINKAGE section describes data made available from another program through the CALL statement. The data structure defined in a LINKAGE section should be located in a COPYBOOK. Otherwise, at runtime multiple COBOL programs may try to share data structures which are not similar.

    First level data items can also be defined in the main program as long as there are no structural pieces of information attached to this first level like the length, the format, and so on.

    This rule raises an issue only on the first invalid data item of a LINKAGE` section.

    LINKAGE SECTION.
    
    01 LK-DATA.  *> Noncompliant
    05 LK-LENGTH     PIC S9(04) COMP.
    05 LK-VARIABLE  PIC X(08).
    

    Using the OPEN file statement is costly, and therefore be avoided inside loops. Instead, the file can be saved into a buffer to increase performance.

    PERFORM UNTIL (NOT DA-OK) OR (Y00CIA-CD-RET-PGM = ZERO)
     OPEN INPUT inventory-file
    END-PERFORM.
    

    While it is possible to manually set a primary key value, doing so almost guarantees a key clash at some point. Instead, primary key values should be set by (in descending order of desirability):

    • automatic generation by the database via a column definition such as `PROD_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1, NO CACHE)

    • the Generate_Unique() function

    • a value pulled directly from a sequence, like so: nextval for SEQ_PRODUCT

    This rule raises an issue when an INSERT` statement assigns values to identity columns that are configured to always generate their values.

    Note That this rule raises issues only when a database catalog is provided during the SonarQube analysis.

    CREATE table my_table (
     column_a integer GENERATED ALWAYS AS IDENTITY primary key not null,
     column_b varchar(50)
    );
    
    INSERT into my_table (column_a, column_b)
    VALUES (1, 'Hello World');  -- Noncompliant
    

    In general, the clause INDEXED BY should be used whenever possible when handling COBOL tables. If it’s not possible, then avoid using a numeric display variable to access the table’s elements. Instead, use a BINARY/COMP variable, which the processor can handle more efficiently.

    01 SUBS PIC 9(5).
       01 INVENTORY-RECORD.
          05 Field-A PIC X OCCURS 10000 TIMES.
       ...
       PERFORM VARYING SUBS FROM 1 BY 1 UNTIL SUBS > 10000
         MOVE ITEM1 TO Field-A (SUBS)      *> Noncompliant
       END-PERFORM.
    

    In cross-site scripting attacks, attackers insert attack scripts into your pages. Because no system is fool-proof, it may not be enough to screen the data that’s submitted to an application. You should also escape any content sent to the user so that any malicious code that may have escaped your input screening is neutralized. Specifically, the characters crucial to forming HTML must be escaped:

    ||turn||into||

    |&|&amp;|

    |<|&lt;|

    |>|&gt;|

    |“|&quot;|

    |’|&#x27;|

    |/|&#x2F;|

    This rule raises an issue for anything sent to WEB.

    ...
    EXEC SQL
    SELECT NAME
    INTO :PNAME
    FROM PRODUCT
    WHERE ID = :PRODUCT_ID
    END-EXEC.
    
    EXEC CICS
    WEB SEND  *> Noncompliant
    FROM(PNAME)
    *> ...
    END-EXEC.
    

    Shared coding conventions allow teams to collaborate efficiently. This rule checks that paragraph names match a provided regular expression.

    PROCEDURE DIVISION.
    
    Do_The_Thing.           *> Noncompliant
    

    COBOL programs that include EXEC SQL INCLUDE statements must be pre-processed with an IBM DB2 precompiler or coprocessor before compilation. The precompiler does not require a period after the closing END-EXEC, but the coprocessor does. For portability, a period should always be used.

    EXEC SQL INCLUDE ... END-EXEC  *> Noncompliant; '.' missing
    

    Since databases don’t offer “Are you sure?” dialogs, it’s best to be very certain of what you’re changing before you do it. `UPDATE and DELETE statements that don’t precisely limit their effects to single rows risk changing more than was intended. That’s why they should be reviewed carefully.

    This rule raises an issue when an UPDATE or DELETE statement’s WHERE clause does not use precisely either a unique index or all parts of the table’s primary key. That includes both cases where they are omitted in whole or in part, and when they are used but could still describe multiple rows. E.G. WHERE AGE = 34, and WHERE TABLE_ID > 0 AND TABLE_ID < 40`.

    Note That this rule raises issues only when a database catalog is provided during the SonarQube analysis.

    CREATE table my_table (
     compound_a integer not null,
     compound_b integer not null,
     column_c varchar(50),
     primary key (compound_a, compound_b)
    );
    
    DELETE FROM my_table
    WHERE compound_b=4;  -- Noncompliant
    

    The comparison of numeric values of different formats is inefficient. For instance, comparing a `COMP-3 with a COMP-4 causes a performance drag because conversions are required under the covers before the comparison.

    This rule raises an issue when variables with different USAGE` clauses, or different numbers of decimal places are compared.

    01 SUB1 PIC 9999 BINARY
    01 WS-DISPLAY-1	PIC 9(12)
    01 WS-PACKED-DEC PIC 9(12)V9(2) COMP-3
    01 WS-BIN PIC S9999 COMP-4
    01 WS-DISPLAY-2	PIC 9(4)
    
    PERFORM VARYING SUB1 FROM WS-DISPLAY-1
    BY WS-PACKED-DEC
    UNTIL WS-BIN > WS-DISPLAY-2  *> Noncompliant
    * ...
    END-PERFORM
    

    The rule S1279 (“DISPLAY” should not be used) is fully preventing the usage of the DISPLAY statement whereas in same cases it may be useful to output some data to SYSOUT. However, the output of a call to DISPLAY UPON CONSOLE is unlikely to be viewed by someone because the output is displayed on the console and nowadays no one is in front of the console to see if something is happening.

    PROCEDURE DIVISION.
    ...
    DISPLAY "Error Occurred!!!" UPON CONSOLE *> Noncompliant
    ...
    

    Moving a large string into a small field will result in data truncation with data lost from the right side of the string.

    01 ALPHA   PIC X(4).
    *> ...
    
    MOVE "Now is the time" TO ALPHA *> Noncompliant. Becomes "Now "
    

    Copybooks should be used only to share data definitions or logic. The following keywords relate to the nature or structure of a COBOL program, and should be defined directly in the source code of the COBOL program:

    • `IDENTIFICATION DIVISION.

    • PROGRAM-ID xxxxxxxx.

    • AUTHOR. yyyyyyyyyyy.

    • INSTALLATION. zzzzzz.

    • DATE-WRITTEN. zzzzzz.

    • DATE-COMPILED. zzzzzz.

    • ENVIRONNEMENT DIVISION.

    • CONFIGURATION SECTION.

    • SOURCE-COMPUTER. xxxxxx.

    • OBJECT-COMPUTER. xxxxxx.

    • SPECIAL-NAMES. DECIMAL-POINT IS COMMA.

    • I-O CONTROL.

    • FILE-CONTROL.

    • DATA DIVISION.

    • FILE SECTION.

    • WORKING-STORAGE SECTION.

    • SCREEN.

    • REPORT.

    • INPUT-OUTPUT SECTION.

    • LINKAGE SECTION.

    • PROCEDURE DIVISION.`

    IDENTIFICATION DIVISION.
    DATA DIVISION.
    LINKAGE SECTION.
    COPY CSCEMOD1.
    MOVE A TO B.
    

    A primary key uniquely identifies a row in a database table, and should be considered immutable. Primary key values may be used in foreign keys in other tables, as well as in external systems. Changing such a value, even with the best of motivations, is likely to wreak havoc on the system’s data integrity and potentially across other systems as well.

    Note That this rule raises issues only when a database catalog is provided during the SonarQube analysis.

    UPDATE USERS
    SET USER_ID = :new-id, USER_NAME = :new-name  *> Noncompliant
    WHERE USER_ID = :input
    

    When the FILE STATUS is not specified on a file, any read operations on the file should handle the “AT END” or “INVALID KEY” conditions.

    SELECT MY_FILE
    ASSIGN TO 'foobar.txt'
    ORGANIZATION IS SEQUENTIAL.
    ...
    READ MY_FILE
    NOT AT END PERFORM COMPUTE_LINE
    END-READ.
    

    There’s no point in selecting columns in a cursor that aren’t actually referenced in the relevant FETCH statement. Instead, either pare down the cursor to select only what you actually need, or FETCH the other columns.

    EXEC SQL
        DECLARE C-SQL-CURSOR CURSOR
          SELECT COLUMN1
                ,COLUMN2  -- Not fetched
                ,COLUMN3  -- Not fetched
            FROM TBLWTABLE
          WITH UR
      END-EXEC.
    
      …
    
      EXEC SQL
        FETCH C-SQL-CURSOR  -- Noncompliant
        INTO  :H-COLUMN1
      END-EXEC
    

    Program/file names offer only very limited space for indicating program function, which is why you should take advantage of the ability to specify a program `TITLE. Omitting the TITLE statement will result in a default, uncommunicative TITLE value being printed at the top of each page of the source listing. Instead, you should write an expressive title that gives a clear impression of the program’s function.

    This rule raises an issue when a there is no TITLE before the IDENTIFICATION DIVISION. Ideally, TITLE` will be the first line of a program, but it cannot be placed before compiler options.

    * Copyright (c) 2012 MyCo. All rights reserved.  *> Noncompliant
       IDENTIFICATION DIVISION.
    

    The number of RECORDS or CHARACTERS specified in a BLOCK CONTAINS clause is used to determine block size. Specify 10 RECORDS, and the block will be exactly 10x the length of the record. But that may not be the right size, depending on the environment. Instead, it is considered a best practice to specify 0 RECORDS, so the block size will be calculated automatically.

    FD OUTFILE1
           BLOCK CONTAINS 32760 RECORDS     >* Noncompliant
           RECORDING MODE V.
       FD OUTFILE2
           BLOCK CONTAINS 1024 CHARACTERS.  >* Noncompliant
    

    If the second procedure of a PERFORM THRU is not defined after the first one, the source code is semantically incorrect and the program doesn’t behave as expected.

    PERFORM SECOND-P THRU FIRST-P.
    ...
    
    FIRST-P.
    ...
    
    SECOND-P.
    ...
    

    An unused data item block is dead code. Such data item blocks should be removed to increase the maintainability of the program.

    IDENTIFICATION DIVISION.
    PROGRAM-ID. foo.
    
    DATA DIVISION.
    WORKING-STORAGE SECTION.
    01 PERSON.        *> Compliant as sub data item FIRST_NAME is used
    02 FIRST_NAME PIC X(21).
    02 LAST_NAME PIC X(21).
    
    01 ADDR.   *> Noncompliant as no data item in this block is used
    02 STREET PIC X(50).  
    02 TOWN PIC X(50).
    
    PROCEDURE DIVISION.
    
    MOVE "John" TO FIRST_NAME.
    

    Having all branches of an EVALUATE or IF chain with the same implementation indicates a problem.

    In the following code:

    EVALUATE X *> Noncompliant
    WHEN 1
    PERFORM SECTION1
    WHEN OTHER
    PERFORM SECTION1
    END-EVALUATE.
    
    IF X = 1 THEN *> Noncompliant
    PERFORM SECTION1
    ELSE
    PERFORM SECTION1
    END-IF.
    

    If a SQL TABLE is declared but not used in the program, it can be considered dead code and should therefore be removed. This will improve maintainability because developers will not wonder what the variable is used for.

    EXEC SQL
    DECLARE DSN8B10.DEPT TABLE  -- Noncompliant
    ( ...  ) 
    END-EXEC.
    

    An alphanumeric value should not be moved to a numeric field. Because alphanumeric values are stored differently than numeric values, simply moving the bits from one field to the other will yield strange results at best, and crashes at worst.

    Instead, NUMVAL should be used to explicitly convert the alphanumeric value to a numeric one.

    01  MY-STR          PIC X(3) VALUE SPACES.
    01  MY-NUM         PIC 9(3) VALUE ZEROES. 
    *> ...
    MOVE '1'         TO MY-STR                  
    MOVE MY-STR  TO MY-NUM  *> Noncompliant
    

    This rule allows banning some modules.

    CALL UT123.
    CALL UT123L.
    CALL UT123-L.
    CALL WS-UT123.
    

    COPY … SUPPRESS suppresses the inclusion of the copybook contents from the source listing, making it very difficult to gain a complete understanding of what’s happening in the code. This could hinder both maintenance and debugging.

    COPY XX001234 SUPPRESS.  <* Noncompliant
    

    Shared coding conventions allow teams to collaborate efficiently. For maximum readability, this rule checks that the levels, names and PICTURE clauses for all items of the same level and which are subordinate to the same item start in the same column.

    01  ZONE1. 
    03  ZONE2  PIC X(10).
    03   ZONE3 PIC X(10).    *> Noncompliant; name out of line
     03 ZONE4  PIC X(10).    *> Noncompliant; level out of line
    03  ZONE5   PIC X(10).   *> Noncompliant; PIC out of line
    

    Performing math on variables that are declared - explicitly or implicitly - as `DISPLAY or NATIONAL is much less efficient than on COMPUTATIONAL, COMP, or BINARY variables. That’s because COMP variables, for instance, are defined for binary storage, which makes math on them more efficient. That’s why values that are going to be used primarily for math should be declared with a math type. When math isn’t a primary use, it may not make sense to change the declared type, but MOVEing the value to a COMP variable and performing the math on it instead would.

    It is important to note however, that COMPUTATIONAL, COMP, and BINARY` formats should be used with caution if the variable will be passed to other systems which may not use the same storage format.

    01 W-AMOUNT-VALUE PIC 9(17).
    01 W-AMOUNT-DECIMAL PIC 9.
    
    COMPUTE W-CONV-AMOUNT = W-AMOUNT-VALUE * 10 ** W-AMOUNT-DECIMAL  *> Noncompliant
    

    Afin de ne pas perturber via la programmation, les paramètres positionnés sur les BIND PACKAGE pour des environnements de type 24/24 7/7, il est important de vérifier que les ordres de SELECT simples ou dans les DECLARE CURSOR que les mots clés WITH RR, WITH RS er WITH CS ne soient pas positionnés. Le seul mot clé accepté est WITH UR.

    S’assurer que sur les ordres de SELECT (simple ou mis dans des DECLARE CURSOR) que les mots clés WITH RR, WITH RS er WITH CS ne soient pas positionnés.

    EXEC SQL DECLARE CLEC_0 CURSOR WITH HOLD
                    	FOR SELECT	C_BQ
                              		,C_CARNT_ORDREB
                              		,N_REF_ORDREB…..
          FROM       S1ORDCOU
          WHERE
    ( C_BQ               >=  :TORD-C-BQ               ) AND NOT
    ( C_BQ                =  :TORD-C-BQ                 AND…..
    ORDER BY C_BQ,C_CARNT_ORDREB,N_REF_ORDREB
    FOR FETCH ONLY
    WITH RR
    END-EXEC.
    

    There is such a thing as software that’s too helpful, and that’s the case with DB2’s implicit casting of host variables used in `WHERE clauses. If for instance you compare a varchar column with the value of a numeric host variable, starting with version 10, DB2 will silently convert the numeric value to a string - at a potentially huge performance cost.

    This rule raises an issue when the type of a variable used with a SQL WHERE` clause does not match the underlying type of the column to which it is compared.

    TODO
    

    Using more than one OF clause to access a data item can quickly decrease the readability of the source code. Either some OF clauses are optional and should be removed, or there are too many intersections between several data structures and those intersections should be removed.

    01 EMPLOYEE. 
    05 MOTHER-IN-LAW. 
    10 NAME PIC X(20). 
    05 FATHER-IN-LAW. 
    10 NAME PIC X(20). 
    ... 
    01 CUSTOMER. 
    05 MOTHER-IN-LAW. 
    10 NAME PIC X(20). 
    05 FATHER-IN-LAW. 
    10 NAME PIC X(20). 
    ... 
    
    MOVE MY_VALUE TO NAME OF MOTHER-IN-LAW OF CUSTOMER
    

    It is fairly normal for COBOL development teams to decide to work either with sections or with paragraphs and to make this choice a standard.

    When sections are used, it is also normal to define another standard: “End every section definition with an empty paragraph definition, or a paragraph containing only a terminating statement”.

    This empty paragraph can then be jumped to with a `GO TO statement to stop the execution of a section.

    Accepted terminating statements in the otherwise-empty ending paragraph are: EXIT, EXIT PROGRAM, STOP RUN, and GO BACK`.

    FIRST_SECTION SECTION.
    ...
    
    SECOND_SECTION SECTION.
    ...
    SECOND_SECTION_END.
    

    Host variables are used for passing data back and forth from the database to a COBOL program via SQL. In order to keep that transmission clear and free of errors, the format of each host variable should match its corresponding database column type.

    This rule raises an issue when column and corresponding host variable don’t match in terms of numeric vs character data, and when the host variable is smaller than the column width.

    TODO
    

    88-level variables, also known as “condition name” variables, represent possible values of the “conditional variables” they’re tied to. An unused “condition name” variable is dead code. Such variables should be removed to increase the maintainability of the program.

    01 COLOR PIC X.
    88 COL-YELLOW VALUE 'Y'.
    88 COL-GREEN VALUE 'G'. *> Noncompliant; not used
    88 COL-RED VALUE 'R'.
    
    * ...
    IF COL-YELLOW 
    * ...
    END-IF
    IF COL-RED 
    * ...
    END-IF
    

    Any statement after a STOP RUN or GOBACK is unreachable and therefore dead code which should be removed.

    PARAGRAPH1.  
    MOVE A TO B.         
    STOP RUN. 
    MOVE B TO C.
    

    When a FILE STATUS is declared on a file, it should be tested immediately after IO operations.

    IDENTIFICATION DIVISION.
       PROGRAM-ID. foo.
    
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
         SELECT TEST-FILE
           ASSIGN TO 'foobar.txt'
           ORGANIZATION IS SEQUENTIAL
           FILE STATUS WS-TEST-FILE-STATUS.
    
       DATA DIVISION.
       FILE SECTION.
       FD TEST-FILE
         LABEL RECORDS ARE STANDARD.
         01 TEST-RECORD.
         05 USERNAME PIC XX.
    
       WORKING-STORAGE SECTION.
         01 WS-TEST-FILE-STATUS PIC X(42).
    
       PROCEDURE DIVISION.
    
      * Non-Compliant, TEST-FILE has a FILE STATUS variable which must be used
        OPEN INPUT TEST-FILE.
    
       END PROGRAM foo.
    

    Every paragraph should be commented to explain its goal and how it works. This comment can be placed either just before or just after the paragraph label. Moreover paragraphs used to close a module can be left uncommented.

    PROCEDURE DIVISION.
    
    * Some comments
    CORRECTLY-COMMENTED-PARAGRAPH1.             *>  Compliant, the comment is just before
    
    ANOTHER-CORRECTLY-COMMENTED-PARAGRAPH1.     *>  Compliant, the comment is just after
    * Some comments
    ...
    
    UNCORRECTLY-COMMENTED-PARAGRAPH1.           *> Not Compliant
    ...
    
    *-------
    UNCORRECTLY-COMMENTED-PARAGRAPH2.           *> Not Compliant as the comment is empty
    ...
    
      PERFORM P1 THRU P2.
    ...
    
    *Some comments                                  *> Compliant
    P1.
      ....
    
    
    P2.                                         *> No violation as the this P2 paragraph close a module
       MOVE A TO B.
       ...
       EXIT.
    

    Aligning common keywords in a series of statements makes the code easier to read. therefore, it is better to align the TO keywords in a series of successive MOVE statements.

    MOVE "Hi There" TO field
    MOVE temp TO b
    MOVE 123 TO item
    

    PERFORM is used to execute a paragraph located somewhere in the program and then, once executed, the execution flow will continue on the line following the PERFORM statement. This is the expected behaviour that can be broken if a GO TO is added in the called paragraph. When mixing PERFORM and GO TO you can quickly be lost on the execution flow and finally don’t get the one you expect. For this reason, calling PERFORM with paragraphs that used GO TO should be avoided.

    PROCEDURE DIVISION.
    DISPLAY-9-LETTERS.
    PERFORM ABC.
    DISPLAY "END OF DISPLAY-9-LETTERS".
    STOP RUN.
    
    ABC.
        DISPLAY "ABC".
        GO TO XYZ.
    
    DEF.
        DISPLAY "DEF".
    
    XYZ.
        DISPLAY "XYZ".
    

    Having two paragraphs with the same name in the same section or in no section at all is bad practice. At best, each copy contains the same code, and the redefinition is simply useless, duplicated code. At worst, the paragraphs contain different logic, potentially leading to confusion and unexpected results as a programmer who was aware of the first paragraph definition inadvertently invokes the second. For these reasons, paragraphs with duplicated names should be either removed or renamed.

    LOAD-DATA. 
     EXEC SQL 
         INSERT INTO EMP (EMPNO, ENAME, DEPTNO) 
             VALUES (:EMP-NUMBER, :EMP-NAME, :DEPT-NUMBER) 
     END-EXEC. 
    
    LOAD-DATA. 
     IF EMP-NUMBER = ZERO 
         MOVE FALSE TO VALID-DATA 
         PERFORM GET-EMP-NUM UNTIL VALID-DATA = TRUE 
     ELSE 
         EXEC SQL DELETE FROM EMP 
             WHERE EMPNO = :EMP-NUMBER 
         END-EXEC
         ADD 1 TO DELETE-TOTAL.
     END-IF.
    
    LOAD-DATA. 
     EXEC SQL 
         INSERT INTO EMP (EMPNO, ENAME, DEPTNO) 
             VALUES (:EMP-NUMBER, :EMP-NAME, :DEPT-NUMBER) 
     END-EXEC.
    

    TODO

    Permettre une gestion standardisée de la gestion des dates dans les traitements. Tous les traitements doivent utiliser le module MGDATR03 s’ils ont besoin d’utiliser la date du jour.

    ACCEPT … FROM DATE
    ACCEPT … FROM TIME
    MOVE CURRENT-DATE TO …
    

    Portability issues may restrict which characters should be used in an identifier.

    This rule checks identifier names against a regular expression of disallowed characters. Due to a technical limitation, the COBOL analyzer is not able for the time-being to differentiate lowercase from uppercase characters.

    MOVE DATA-1 TO DATA_2 *> Noncompliant; '_' not allowed
    

    Shared coding conventions allow teams to collaborate efficiently. This rule checks that first level data item names match a provided regular expression.

    WORKING-STORAGE SECTION.
            01 WRONG.                                       > Noncompliant; name doesn't match the pattern "WS-.*"
              02  LINK.                                     > Compliant; this is not first level
    
       LINKAGE SECTION.
             01     DFHCOMMAREA PIC X(1500).                > Compliant; the data item is defined in the LINKAGE SECTION
    

    The EVALUATE statement allows implementing case structures in Cobol. Each case is managed by a WHEN phrase activated by specific test of a variable.The WHEN OTHER phrase allows managing all the cases which have not been taken into account by the previous WHEN phrases. If the variable to be tested contains a new value that is not currently managed then the absence of the WHEN OTHER phrase will lead a situation in which no process will be performed for this value and the program may have uncontrolled or undefined behavior.

    A010-PRINCIPAL.
         EVALUATE  Y5FTAR-PER-ECN-CTS 
           WHEN '01'                   
             MOVE 'A' TO WS-CD-PER-CTS
           WHEN '02'  
             MOVE 'S' TO WS-CD-PER-CTS
           WHEN '04'  
             MOVE 'T' TO WS-CD-PER-CTS
           WHEN '12'     
             MOVE 'M' TO WS-CD-PER-CTS
         END-EVALUATE.
    

    There is no good reason to keep an empty and therefore valueless section. Such sections should be removed.

    FIRST SECTION.
    MOVE A TO B.
    
    SECOND SECTION.  *> Noncompliant; empty
    
    THIRD SECTION.
    
    someParagraph.
    DISPLAY B.
    

    Moving a large number into a small field will result in data truncation. Generally, numeric values are truncated from the left. However, in the case of floating point values, when the target field has too little precision to hold the value being moved to it, decimals will be truncated (not rounded!) from the right.

    In any case, data loss is always the result when too-large values are moved to too-small fields.

    01 NUM-A   PIC 9(2)V9.
    *> ...
    
    MOVE 88.89   TO NUM-A  *> Noncompliant. Becomes 88.8
    MOVE 178.7   TO NUM-A  *> Noncompliant. Becomes 78.7
    MOVE 999.99 TO NUM-A  *> Noncompliant. Truncated on both ends; becomes 99.9
    

    When using CICS XCTL or CICS LINK, it is a bad practice not to specify the length of the communication area.

    EXEC CICS LINK PROGRAM ('SPI2TCV') COMMAREA (SPI-PARMCICS)  RESP (WS-RESP)  *> Noncompliant
    
    EXEC CICS XCTL PROGRAM ('P4DERROR') COMMAREA (Y4DERROR)  *> Noncompliant
    

    When a closable statement contains nested statements, it can quickly become difficult to see which statements are nested and which are not. That’s why ending a list of nested statements with END-${STATEMENT-NAME} is advised.

    READ DF-PARAM-SPILOTE AT END
    GO TO F-LECT-SPILOTE.
    

    OS/VS COBOL accepted the EXHIBIT statement, but IBM Enterprise COBOL does not. With IBM Enterprise COBOL, the DISPLAY statement must be used instead.

    IDENTIFICATION DIVISION.
       PROGRAM-ID. foo.
    
       DATA DIVISION.
    
       WORKING-STORAGE SECTION.
         01 WS-FOO PIC X(42).
         01 WS-BAR PIC X(42).
    
       PROCEDURE DIVISION.
      * Non-Compliant
         EXHIBIT NAMED WS-FOO WS-BAR.
       END PROGRAM foo.
    

    The binary algorithm used by `SEARCH ALL is far more efficient for large tables than the one used by SEARCH. While it’s not always possible to use SEARCH ALL, it should be the preferred algorithm.

    This rule raises an issue when tables with more than the specified number of possible entries are searched using SEARCH`.

    01  MY-TABLE.
    05 MY-TAB-ELEM OCCURS 300000
     INDEXED BY MY-TAB-IND.
    10 MY-ATTR1                        PIC X(07).
    10 MY-ATTR2                        PIC X(07).
    10 MY-ATTR3                        PIC X(07).
    
    01  MY-TAB2.
    05 MY-TAB2-ELEM          OCCURS 300000
     ASCENDING MY-ATTR1  *> Key is defined. Why not use it?
     INDEXED BY MY-TAB-IND.
    10 MY-ATTR1                        PIC X(07).
    10 MY-ATTR2                        PIC X(07).
    10 MY-ATTR3                        PIC X(07).
    
    01  MY-TAB-IND             PIC 9(08).
    
    
    SEARCH MY-TAB-ELEM.  *> Noncompliant; define a key & use binary search
       AT END...
    
    SEARCH MY-TAB2-ELEM.  *> Noncompliant
       AT END...
    

    Credentials should never be included in comments. Doing so means that anyone who has access to the code also has access to the database.

    This rule flags each instance of “password” in a comment

    * Password is "red!"
    

    Putting multiple statements on a single line lowers the code readability and makes debugging the code more complex.

    Unresolved directive in <stdin> - include::{noncompliant}[]

    Write one statement per line to improve readability.

    Unresolved directive in <stdin> - include::{compliant}[]

    IF x > 0 THEN DISPLAY "positive". *> Compliant by exception
    

    The complexity of an expression is defined by the number of &&, || and condition ? ifTrue : ifFalse operators it contains.

    A single expression’s complexity should not become too high to keep the code readable.

    IDENTIFICATION DIVISION.
       PROGRAM-ID. foo.
    
       PROCEDURE DIVISION.
    
      * Noncompliant, 4 operands are found, higher than the maximum allowed 3
           IF WS-FOO(1) = 1 OR
              WS-FOO(2) = 2 OR
              WS-FOO(3) = 3 OR
              WS-BAR = 4 OR
              WS-BAZ = 5 OR
              WS-QUX = 42
           END-IF.
       END PROGRAM foo.
    

    Allowing an application to dynamically change the structure of a database at runtime is very dangerous because the application can become unstable under unexpected conditions. Best practices dictate that applications only manipulate data.

    EXEC SQL
    CREATE TABLE INVENTORY
                 (PARTNO         SMALLINT     NOT NULL,
                  DESCR          VARCHAR(24 ),
                  PRIMARY KEY(PARTNO))
    END-EXEC.
    
    EXEC SQL
    DROP TABLE EMPLOYEE RESTRICT
    END-EXEC.
    
    EXEC SQL
    ALTER TABLE EQUIPMENT
     DROP COLUMN LOCATION CASCADE
    END-EXEC.
    

    Development tools and frameworks usually have options to make debugging easier for developers. Although these features are useful during development, they should never be enabled for applications deployed in production. Debug instructions or error messages can leak detailed information about the system, like the application’s path or file names.

    SOURCE-COMPUTER. IBM-370.
    

    Magic numbers make the code more complex to understand as it requires the reader to have knowledge about the global context to understand the number itself. Their usage may seem obvious when writing the code, but it may not be the case for another developer or later once the context faded away. -1, 0, and 1 are not considered magic numbers.

    DATA DIVISION.
    WORKING-STORAGE SECTION.
        01 WS-COUNT PIC 9(1) VALUE 0.
    PROCEDURE DIVISION.
    A-PARA.
    PERFORM B-PARA UNTIL WS-COUNT=5                      *> Noncompliant - 5 is a magic number
    STOP RUN.
    
    B-PARA.
    DISPLAY "Count:"WS-COUNT.
    ADD 1 TO WS-COUNT.
    

    SQL queries that use EXISTS subqueries are inefficient because the subquery is re-run for every row in the outer query’s table. There are more efficient ways to write most queries, ways that do not use the EXISTS condition.

    SELECT e.name
    FROM employee e
    WHERE EXISTS (SELECT * FROM department d WHERE e.department_id = d.id AND d.name = 'Marketing')
    

    Although the WHERE condition is optional in a SELECT statement, for performance and security reasons, a WHERE clause should always be specified to prevent reading the whole table.

    SELECT * FROM db_persons INTO us_persons WHERE country IS 'US'
    

    Each source file should start with a header stating file ownership and the license which must be used to distribute the application.

    This rule must be fed with the header text that is expected at the beginning of every file.

    *
    * SonarQube, open source software quality management tool.
    * Copyright (C) 2008-2013 SonarSource
    * mailto:contact AT sonarsource DOT com
    *
    * SonarQube is free software; you can redistribute it and/or
    * modify it under the terms of the GNU Lesser General Public
    * License as published by the Free Software Foundation; either
    * version 3 of the License, or (at your option) any later version.
    *
    * SonarQube is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    * Lesser General Public License for more details.
    *
    * You should have received a copy of the GNU Lesser General Public License
    * along with this program; if not, write to the Free Software Foundation,
    * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
    *
    

    The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. However, redundant pairs of parentheses could be misleading and should be removed.

    COMPUTE x = (y / 2 + 1).  *> Compliant even if the parenthesis are ignored by the compiler
    COMPUTE y = 2 * ((x + 1)).  *> Noncompliant
    

    Conditional expressions which are always true or false can lead to unreachable code.

    SET FOO TO FALSE
    
    IF FOO IS TRUE   *> Noncompliant
    DISPLAY "..."           *> never executed
    END-IF.
    
    IF FOO IS NOT TRUE OR BAR IS TRUE *> Noncompliant; BAR is never evaluated
    DISPLAY "..."
    END-IF.
    

    There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead.

    SET NAME TO NAME.    *> Noncompliant
    MOVE NAME TO NAME.   *> Noncompliant
    COMPUTE NAME = NAME. *> Noncompliant
    EXEC SQL
    UPDATE PERSON
    SET NAME = NAME  -- Noncompliant
    WHERE ID = :PERSON_ID
    END-EXEC.
    

    Duplicated string literals make the process of refactoring complex and error-prone, as any change would need to be propagated on all occurrences.

    PROCEDURE DIVISION.
    
       DISPLAY "Firstname: ".
      *...
       DISPLAY "Firstname: ".
      *...
       DISPLAY "Firstname: ".
    

    SELECT * should be avoided because it releases control of the returned columns and could therefore lead to errors and potentially to performance issues.

    SELECT * 
       FROM persons 
       INTO newyorkers 
       WHERE city = 'NEW YORK'
    

    Developers often use TODO tags to mark areas in the code where additional work or improvements are needed but are not implemented immediately. However, these TODO tags sometimes get overlooked or forgotten, leading to incomplete or unfinished code. This rule aims to identify and address unattended TODO tags to ensure a clean and maintainable codebase. This description explores why this is a problem and how it can be fixed to improve the overall code quality.

    DIVIDE 5 BY DIVISOR GIVING QUOTIENT. *> TODO ensure DIVISOR is not zero
    

    In a Zen-like manner, “NULL” is never equal to anything, even itself. Therefore comparisons using equality operators will always return `False, even when the value actually IS NULL.

    For that reason, comparison operators should never be used to make comparisons with NULL; IS NULL and IS NOT NULL should be used instead. This extends as well to empty string (""), which is equivalent to NULL` for some database engines.

    UPDATE books
    SET title = 'unknown'
    WHERE title = NULL -- Noncompliant
    

    Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source.

    In the past, it has led to the following vulnerabilities:

    • CVE-2019-13466

    • CVE-2018-15389

    Credentials should be stored outside of the code in a configuration file, a database, or a management service for secrets.

    This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list.

    It’s recommended to customize the configuration of this rule with additional credential words such as “oauthToken”, “secret”, …​

    DISPLAY env-name-pwd UPON ENVIRONMENT-NAME
    ACCEPT env-val-pwd FROM ENVIRONMENT-VALUE *> Compliant
    
    DISPLAY env-name-uid UPON ENVIRONMENT-NAME
    ACCEPT env-val-uid FROM ENVIRONMENT-VALUE *> Compliant
    
    EXEC SQL
    CONNECT :env-name-uid
    IDENTIFIED BY :env-val-pwd
    AT :MYCONN
    USING :MYSERVER
    END-EXEC.
    

    Control flow constructs like if-statements allow the programmer to direct the flow of a program depending on a boolean expression. However, if the condition is always true or always false, only one of the branches will ever be executed. In that case, the control flow construct and the condition no longer serve a purpose; they become gratuitous.

    IF BAR = 4
    *  Noncompliant: due to the nesting IF statement, we know that BAR = 4 here and so 
    *  what's the point of testing again that BAR = 4 ?
     IF FOO = "a" AND BAR = 4
       DISPLAY "something"
     END-IF.
     ...
    END-IF
    

    SQL statements should not contain dynamic clauses

    EXEC SQL SELECT * FROM tableName END-EXEC.
    

    Having two WHEN clauses in the same EVALUATE statement or two branches in the same IF structure with the same implementation is at best duplicate code, and at worst a coding error.

    IF X = 1
    MOVE A TO B.
    PERFORM SECTION1
    ELSE
    IF X > 10
    PERFORM SECTION2
    ELSE                *> Noncompliant
    MOVE A TO B.
    PERFORM SECTION1
    END-IF
    END-IF.
    
    CssCommon
    twitterlinkedin
    Powered by Mintlify