Quotes

Friday, August 4, 2017

ESQL Code conventions in Websphere Message Broker Part 2

5. Comments

The discussion below classifies ESQL comments into one of two classes:
  • Header comments, used to summarize and demarcate a section of an ESQL file
  • Implementation comments, used to clarify the meaning of a piece of ESQL logic.

5.1. Header comments

5.1.1. File header

An ESQL file should always begin with a file-header comment that provides the name of the file, a brief synopsis of the purpose of the file, the copyright, and author information. The example below illustrates one possible format for such a header, but any suitable alternative that clearly conveys the same information is acceptable. The header is 80 characters in length. The description text should consist of complete sentences, wrapped as needed without using hyphenation. List each author on a separate line.

5.1.2. Module header

Every module definition must be preceded by a module header comment. A module header contains descriptive text that consists of complete sentences, wrapped as needed without using hyphenation:
1
2
3
4
/*
 * Module description goes here
 *
 */

5.1.3. Procedure header

Every procedure definition must be preceded by a procedure header comment. A procedure header contains descriptive text that consists of complete sentences, wrapped as needed without using hyphenation. This header should also name and describe each of the parameters handled by the procedure, classifying them as type IN, OUT, or INOUT. The parameter descriptions need not consist of complete sentences -- brief, descriptive phrases should suffice. However, they should be preceded by a hyphen and properly aligned with one another:
1
2
3
4
5
6
7
8
9
10
/*
 * Procedure description goes here.
 *
 * Parameters:
 *
 * IN:     REFERENCE parameter1 - Description goes here.
 * INOUT: INTEGER   parameter2 - Description goes here.
 * OUT:    TIMESTAMP result     - Description goes here.
 *
 */

5.1.5. Function header

Function headers are essentially the same as procedure headers:
1
2
3
4
5
6
7
8
9
10
11
12
/*
 * Function description goes here.
 *
 * Parameters:
 *
 * IN:     REFERENCE parameter1 - Description goes here.
 * INOUT: INTEGER   parameter2 - Description goes here.
 * OUT:    TIMESTAMP result     - Description goes here.
 *
 * RETURNS: BOOLEAN – Description goes here.
 *
 */

5.2. Implementation comments

Add comments to ESQL source code to clarify program logic and convey information that is not immediately obvious from inspecting the code. Do not add too many comments -- they can become redundant, complicate code maintenance, and get out of date as the software evolves. In general, too many comments indicate poorly written code, because well written code tends to be self explanatory. Implementation comments can be written in single-line, block, or trailing forms, as described below.

5.2.1. Single-line comments

A single-line comment is a short comment that explains and aligns with the code that follows it. It should be preceded by a single blank line and immediately followed by the code that it describes:
1
2
3
4
-- Check for the condition
IF condition THEN
    SET z = x + y;
END IF;

5.2.2. Block comments

Block comments are used to provide descriptions of ESQL files, modules, procedures, and functions. Use Block comments at the beginning of each file and before each module, procedure, and function. You can also use them anywhere in an ESQL file. Block comments inside a function or procedure should be indented at the same level as the code they describe. Precede a block comment by a single blank line and immediately follow it by the code it describes. Because shorter comments with expressive code are always preferable to lengthy block comments, block comments should be rarely used within a procedure or function. Example of a block comment:
1
2
3
4
5
6
7
8
/*
 * Here is a block comment to show an example of comments
 * within a procedure or function.
 *
 */
IF condition THEN
    SET z = x + y;
END IF;

5.2.3. Trailing comments

Trailing comments are brief remarks on the same line as the code they refer to. Indent these comments to clearly separate them from the relevant code. If several trailing comments relate to the same segment of code, align the comments with one another. Trailing comments are usually brief phrases and need not be complete sentences:
1
2
3
4
5
IF condition THEN
    SET z = x + y;           -- trailing comment 1
ELSE
    SET z = (x - y) * k;    -- comment 2, aligned with comment 1
END IF;

6. Style guidelines

6.1. Line wrapping and alignment

Lines of ESQL source code should be wrapped and aligned according to the following guidelines:
  • Every statement should be placed on a separate line.
  • Lines longer than 80 characters should be avoided as they exceed the default width of many terminals and development tools.
  • The unit of indentation used to align ESQL source code should be four characters which is the default setting in the WebSphere Message Broker Toolkit. The specific construction of this indentation, using spaces or tabs, is left to the discretion of the programmer.
  • Line lengths should be limited by breaking lengthy expressions according to the following rules:
  • Lines should be as long as possible, without exceeding 80 characters;
  • Break after a comma;
  • Break before an operator;
  • Break at the highest level possible in the expression;
  • Align a new line with the beginning of the expression at the same level on the preceding line. Should this alignment require deep indentations that produce awkward code, an indentation of eight spaces may be used instead.
The following ESQL code samples illustrate the above rules.
1
2
3
4
5
6
7
8
9
10
11
CREATE FUNCTION function1(IN longExpression1 REFERENCE,
                          IN longExpression2 CHAR,
                          OUT longExpression3 NUMBER,
                          INOUT longExpression4 CHAR)
CALL procedure1(myLongVariable1, myLongVariable2, myLongVariable3,
          myLongVariable4);
SET returnValue = function1(argument1, argument2, argument3,
                            function2(argument4, argument5,
       argument6));
SET finalResult = ((x / variable1) * (variable2 - variable3))
               + (y * variable5);
The ESQL sample below illustrates a case where an indentation of eight spaces should be used instead of the usual alignment to avoid deeper indentations that would result in confusing code.
1
2
3
4
-- INDENT 8 SPACES TO AVOID VERY DEEP INDENT
CREATE PROCEDURE showAVeryLongProcedureName(IN argument1,
        INOUT argument2,
        OUT argument3)
Finally, the ESQL samples below illustrate line wrapping and alignment practices. The first is preferable because the line break is inserted at the highest level possible.
1
2
3
4
SET longName1 = longName2 * (longName3 + longName4 - longName5)
                   + 4 * longname6;                         -- PREFER
SET longName1 = longName2 * (longName3 + longName4
                   - longName5) + 4 * longname6;          -- AVOID

6.2. White space

White space should be used to improve code readability.
  • Insert two blank lines between sections of a ESQL file;
  • Insert one blank line between functions and procedures;
  • Insert one blank line between the variable declarations in a function/procedure and its first statement;
  • Insert one blank line before a block or single-line comment;
  • A blank space should follow each comma in any ESQL statement that makes use of commas outside of a string literal;
  • All binary operators should be separated from their operands by spaces.
1
2
SET a = c + d;
SET a = (a + b) / (c * d);

7. Statements

Each line should contain at most one statement. Here are some sample statements.

7.1. DECLARE

Put declarations right after the broker schemas or at the beginning of modules, functions, and procedures. One declaration per line is recommended:
1
2
3
4
5
6
7
8
9
10
-- EXTERNAL variable
DECLARE DAY1 EXTERNAL CHARACTER 'monday';
-- NAMESPACE variable
DECLARE XMLSCHEMA_INSTANCE NAMESPACE 'http://www.w3.org/2001/XMLSchema-instance';
-- CONSTANT
DECLARE HIGH_PRIORITY CONSTANT INTEGER 7;
-- SHARED variable
DECLARE processIdCounter SHARED INTEGER 0;
-- REFERENCE
DECLARE messageType REFERENCE TO Root.XMLNSC.Msg.Type;

7.2. FOR

1
2
3
4
5
DECLARE i INTEGER 1;
FOR source AS Environment.SourceData.Folder[] DO
    ...
    SET i = i + 1;
END FOR;

7.3. IF

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-- IF statement
IF InputBody.Msg.Report = 'PDF' THEN
    SET OutputRoot.XMLNSC.Msg.Type = 'P';
END IF;
-- IF-ELSE statement
IF InputBody.Msg.Report = 'PDF' THEN
    SET OutputRoot.XMLNSC.Msg.Type = 'P';
ELSE
    SET OutputRoot.XMLNSC.Msg.Type = 'X';
END IF;
-- IF-ELSEIF-ELSE statement
IF InputBody.Msg.Report = 'PDF' THEN
    SET OutputRoot.XMLNSC.Msg.Type = 'P';
ELSEIF InputBody.Msg.Report = 'DOC' THEN
    SET OutputRoot.XMLNSC.Msg.Type = 'D';
ELSE
    SET OutputRoot.XMLNSC.Msg.Type = 'X';
END IF;

7.4. LOOP

1
2
3
4
5
6
7
8
9
DECLARE i INTEGER;
SET i = 1;
x : LOOP
    ...
    IF i >= 4 THEN
        LEAVE x;
    END IF;
    SET i = i + 1;
END LOOP x;

7.5. RETURN

1
2
3
4
5
RETURN;
RETURN TRUE;
RETURN FALSE;
RETURN UNKNOWN;
RETURN ((priceTotal / numItems) > 42);

7.6. THROW

1
2
3
4
5
THROW USER EXCEPTION;
THROW USER EXCEPTION CATALOG 'BIPv600' MESSAGE 2951
        VALUES('The SQL State: ', SQLSTATE, 'The SQL Code: ',
               SQLCODE, 'The SQLNATIVEERROR: ', SQLNATIVEERROR,
               'The SQL Error Text: ', SQLERRORTEXT);

7.7. WHILE

1
2
3
4
5
6
-- WHILE statement       
DECLARE i INTEGER 1;
WHILE i <= 10 DO
    SET OutputRoot.XMLNSC.Msg.Count[i] = i;
    SET i = i + 1;
END WHILE;

7.8. CASE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-- CASE function
-- Like ?: Expression in C       
SET OutputRoot.XMLNSC.Msg.Type = CASE InputBody.Msg.Report
        WHEN 'PDF' THEN 'P'
        WHEN 'DOC' THEN 'D'
        ELSE 'X'
        END;      
-- Like SWITCH Expression in C       
CASE InputBody.Msg.Report
WHEN 'PDF' THEN
    SET OutputRoot.XMLNSC.Msg.Type = 'P';
WHEN 'DOC' THEN
    CALL handleDocument();
ELSE
    CALL handleUnkown();
END CASE;

7.9. SELECT

1
2
3
SELECT ITEM segment.No
        FROM ControlRef.Segments.Segment[] AS segment
        WHERE segment.No = currentSegment;

7.10. UPDATE

1
2
3
UPDATE Database.TELEMETRY AS telemetry
        SET bitmap = refEnvTeleSeg.NewBitmap
        WHERE telemetry.TelemetryId = refEnvTeleSeg.Results.TelemetryId;

7.11. INSERT

1
2
3
INSERT INTO Database.TELEMETRY_SEGMENT (TelemetryId, BlockNum, FileSegment)
        VALUES (refEnvTeleSeg.Results.TelemetryId, RefEnvTeleSeg.SegmentNum,
                  ASBITSTREAM(Body));

8. Programming practices

  • Put variables and constants at the broker schema level only when they need to be reused by multiple modules.
  • Initialize variables within DECLARE statements, especially EXTERNAL variables.
  • Declare REFERENCEs to avoid excess navigation of the Message Tree.
  • Specify a direction indicator for all new routines of any type for documentation purposes although the direction indicator (IN, OUT, INOUT) of FUNCTION is optional for each parameter.
  • Make code as concise as possible to restrict the number of statements. This will cut parsing overhead.
  • Use LASTMOVE or CARDINALITY statements to check the existence of fields in the message tree. This would avoid mistakes.
  • Avoid use of CARDINALITY statements inside loops.
  • Avoid overuse of Compute nodes because tree copying is processor heavy: put reusable nodes into sub-flows.
  • Avoid nested IF statements: use ELSEIF or CASE WHEN clauses to get quicker drop-out.
  • Avoid overuse of string manipulation because it is processor heavy: use the REPLACE function in preference to a complete re-parsing.
  • Use parentheses to make the meaning clear. The order of precedence in the arithmetic expressions is:
  • Parentheses
  • Unary operators including unary - and NOT
  • Multiplication and division
  • Concatenation
  • Addition and subtraction
  • Operations at the same level are evaluated from left to right.

9. Code sample

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

BROKER SCHEMA com.ibm.convention.sample
PATH com.ibm.convention.common;
-- First day of the week
DECLARE DAY1 EXTERNAL CHARACTER 'monday';
-- XML schema instance namespace
DECLARE XMLSCHEMA_INSTANCE NAMESPACE 'http://www.w3.org/2001/XMLSchema-instance';
-- High priority message's priority on MQ
DECLARE HIGH_PRIORITY CONSTANT INTEGER 7;
-- A shared counter to generate process id
DECLARE processIdCounter SHARED INTEGER 0;
/*
 * This procedure generates the process id.
 *
 * Parameters:
 *
 * OUT:   CHARACTER processId     - Description goes here.
 *
 */
CREATE PROCEDURE getProcessId(OUT processId CHARACTER)
BEGIN
    BEGIN ATOMIC       
        SET processId = CAST(CURRENT_TIMESTAMP AS CHARACTER FORMAT 'ddHHmmss')
                        || CAST(processIdCounter as CHAR);
        SET processIdCounter = processIdCounter + 1;
    END;
END;
/*
 * This function encodes the input in BASE64 format.
 *
 * Parameters:
 * IN:    BLOB document - Input document for encoding.
 *
 * RETURNS: CHARACTER   – BASE64 encoded string.
 *
 */
CREATE FUNCTION encodeInBASE64 (IN data BLOB)
RETURNS CHARACTER
LANGUAGE JAVA
EXTERNAL NAME "com.ibm.broker.util.base64.encode";
/*
 * This module has the sample code for the article, ESQL code convention.
 */
CREATE COMPUTE MODULE CreateESQLCodeConvention
    CREATE FUNCTION Main() RETURNS BOOLEAN
    BEGIN
        DECLARE processId CHARACTER;  -- Unique identifier of the working process
        CALL getProcessId(processId);
        SET encodedMessage = base64Encode(ASBITSTREAM(InputBody.Msg));
        RETURN TRUE;
    END;
END MODULE;
/*
 * This module filters data base on the message type.
 * It has the sample code of the second module in the ESQL file.
 */
CREATE FILTER MODULE FilterData
    CREATE FUNCTION Main() RETURNS BOOLEAN
    BEGIN
        DECLARE messageType REFERENCE TO Root.XMLNSC.Msg.Type;
        IF messageType = 'P' THEN
            RETURN TRUE;
        ELSEIF messageType = 'D' THEN
            RETURN FALSE;
        ELSE
            RETURN UNKNOWN;
        END IF;   
    END;
END MODULE;

//End