EVALUATION OF SOFTWARE TOOLS - SOFTWARE CODING … · 2008-08-12 · Title: Evaluation of Software...
Transcript of EVALUATION OF SOFTWARE TOOLS - SOFTWARE CODING … · 2008-08-12 · Title: Evaluation of Software...
PREPARATORY COMMISSION FORTHE COMPREHENSIVE NUCLEAR-TEST-BAN TREATY ORGANIZATION
Distr.: LIMITEDEVA-102/01/451
English
EVALUATION OF SOFTWARE TOOLS -
SOFTWARE CODING STANDARD
Summary
This document specifies a set of programming rules or conventions which is intended to besuitable in the context of the evaluation of the maintainability, reliability and portability ofsoftware tools. Some rules have a general scope whereas others only address a givenprogramming language (e.g. C, Java, Perl). Each rule is specified through several itemsincluding justification and examples.
History table
Reference: EVA-102/01/451Title: Evaluation of Software Tools -
Software Coding StandardVersion Purpose of modification Pages concerned Date- Original all 07/17/2001V1p5 Preliminary version subject to changes all 09/17/2001V1p6 Java naming conventions added 126-128 09/24/2002V1p7 Security requirement added 52 12/12/2002
EVA-102/01/451Page 2
EVA-102/01/451Page 3
Contents
1. Introduction ........................................................................................................................ 71.1. Foreword ........................................................................................................................ 71.2. Scope .............................................................................................................................. 71.3. Audience......................................................................................................................... 8
2. Terms and definitions......................................................................................................... 93. Presentation of the rules ................................................................................................... 10
3.1. Organisation of rules .................................................................................................... 103.2. Specification of the rules.............................................................................................. 103.3. Writing conventions ..................................................................................................... 11
4. Summary of the rules ....................................................................................................... 125. Programming rule specification ....................................................................................... 15
5.1. File organisation........................................................................................................... 165.2. Declaration and definition............................................................................................ 315.3. Function usage.............................................................................................................. 415.4. Control flow structuring ............................................................................................... 545.5. Operand usage .............................................................................................................. 725.6. Operator usage.............................................................................................................. 905.7. Expressions................................................................................................................... 975.8. Code typing ................................................................................................................ 1115.9. Naming ....................................................................................................................... 127
6. APPENDIX A: Tables of content by language.............................................................. 1416.1. Rules applicable to all languages ............................................................................... 1416.2. Additional rules for the C language ........................................................................... 1416.3. Additional rules for the Java language....................................................................... 1426.4. Additional rules for the C++ language....................................................................... 1426.5. Additional rules for the Korn shell language ............................................................. 1436.6. Additional rules for the Perl language........................................................................ 143
7. Appendix B: Summary by quality characteristic ........................................................... 1447.1.1. Maintainability ............................................................................................... 1447.1.2. Reliability ....................................................................................................... 1457.1.3. Portability ....................................................................................................... 1457.1.4. Efficiency ....................................................................................................... 146
8. Summary by severity...................................................................................................... 1468.1.1. Severity 1: mandatory .................................................................................... 1468.1.2. Severity 2: recommended............................................................................... 1478.1.3. Severity 3: advisable ...................................................................................... 148
EVA-102/01/451Page 4
Abbreviations
CNES Centre National d’Etudes Spatiales,CSC Computer Software ComponentCSCI Computer Software Configuration ItemCTBT Comprehensive Nuclear-Test-Ban TreatyCTBTO Comprehensive Nuclear-Test-Ban Treaty Organization IDC International Data CentreIEC International Electrotechnical CommissionISO International Organization for StandardizationMISRA Motor Industry Software Reliability AssociationNASA National Aeronautics and Space Administration PTS Provisional Technical SecretariatRD Referenced Document
EVA-102/01/451Page 5
Reference
[RD1] CTBT/PTS/INF.307 Evaluation of IDC applications software: Assessment of Maintainability CTBT/PTS
[RD2] ISO/IEC 9899:1990 (E)Programming languages -- CISO/IEC, 1990.
[RD3] ISO/IEC FDIS 9126-1:1999Information Technology - Software product quality - Part 1: Quality model.ISO/IEC, 1999.
[RD4] SEL-94-003C Style Guide.NASA National Aeronautics and Space Administration, 1994.
[RD5] Guidelines for the use of C language in vehicle based software.MISRA The Motor Industry Software Reliability Association, 1998.
[RD6] Recommended C Style and Coding Standards.www.cs.umd.edu/users/cml/cstyle/indhill-cstyle.htmlUniversity of Maryland, Department of Computer Science.
[RD7] MPM-53-00-06 Ed.2 - Rév.0Référentiel d’instructions - Méthode et procédures -Règles essentielles pour l’utilisation du langage CCNES Centre National d’Etudes Spatiales, 1995.
[RD8] ISO/IEC 14882:1998 (E)Programming languages -- C++ISO/IEC, 1998.
[RD9] RNC-CNES-Q-80-527 Ed.2 - Rév.0Référentiel normatif - Méthode et procédure -Règles et recommandations pour l’utilisation du langage JavaCNES Centre National d’Etudes Spatiales, 13 mars 2001.
[RD10] ISO/IEC 14882:1998 (E)Programming languages -- C++ISO/IEC, 1998.
[RD11] ISO/IEC 9945-2 [IEEE/ANSI Std 1003.2-1992 & IEEE/ANSI 1003.2a-1992]Part 2 : Shell and UtilitiesISO/IEC, 1993.
EVA-102/01/451Page 6
[RD12] IEEE/ANSI 1003.2dIEEE Standard for Information Technology -Portable Operating System Interface (POSIX)Part 2 : Shell and Utilities-Amendment 1: Batch EnvironmentIEEE/ANSI, 1994.
[RD13] MPM-53-00-16 Ed.3 - Rév.0Référentiel d’instructions - Méthode et procédures -Règles essentielles pour l’utilisation du Shell UNIXCentre National d’Etudes Spatiales, 2000.
EVA-102/01/451Page 7
1. INTRODUCTION
1.1. Foreword
This document has been funded by the Evaluation Section and developed by the IDCDivision, with inputs from external expertise.Its first intent was to formalise the maintainability evaluation requirements for C software theconformity to which is verified by the evaluation modules proposed in the annexes of"Evaluation of IDC applications software: Assessment of Maintainability" [RD1].
It has been further extended to other software characteristics (e.g. reliability, portability) aswell as other programming languages (e.g. Java, Perl). This results in intentionallygeneralising some concepts. Thus, some readers may find a certain lack of accuracy in thedescription of some rules. But, this state has been considered as of lower interest than theimplicit increase of the scope of the document.
1.2. Scope
In term of style and expressiveness, the programming languages such as C ([RD2]), C++([RD10]), Java, Perl or Korn shell ([RD11]) can be used to write well laid out, structures andexpressive code. It can also be used to write perverse and extremely hard-to-understand code.Clearly, the latter is not acceptable in the context of the IDC applications software.
The establishment of a common programming style intent to facilitate maintaining the codedeveloped by more than one programmer as well as making it easier for several people to co-operate in the development and maintenance of the same program. It also contributes toreducing the risk of coding valid but unintended constructs which may undermine the level ofreliability and portability of the program.
This document defines programming rules for the evaluation of the maintainability, reliability,efficiency and portability and the following associated sub-characteristics as defined inISO/IEC 9126-1 [RD3] (see also chapter 4) of the IDC applications software: (a) adaptability,(b) analysability,(c) changeability,(d) fault tolerance,(e) maturity,(f) time behaviour,(g) resource behaviour,(h) stability,(i) testability.
Most programming styles are somewhat arbitrary, and this one is no exception even if therules correspond to state of the art and best practices in the field of software industry ([RD4],[RD5], [RD6], [RD7]). However, using a consistent programming style throughout aparticular CSC or CSCI is important because it allows people other than the author to easilyunderstand and therefore maintain the code. One more thing to keep in mind is that whenmodifying an existing source file, the modifications should be coded in the same style as thefile being modified.
EVA-102/01/451Page 8
1.3. Audience
This document addresses people in charge of evaluating the maintainability, reliability,efficiency and portability of the IDC applications software.
It can also be used by people developing and maintaining the IDC applications software as aset of quality requirements.
EVA-102/01/451Page 9
2. TERMS AND DEFINITIONS
Adaptability:Capability of the software product to be adapted for different specified environments withoutapplying actions or means other than those provided for this purpose for the softwareconsidered. [RD3]
Analysability:Capability of the software product to be diagnosed for deficiencies or causes of failures in thesoftware, or for the parts to be modified to be identified. [RD3]
Changeability:Capability of the software product to enable a specified modification to be implemented.[RD3]
Efficiency:Capability of the software product to provide appropriate performance, relative to the amountof resources used, under stated conditions. [RD3]
Maturity:Capability of the software product to avoid failure as a result of faults in the software. [RD3]
Fault tolerance:Capability of the software product to maintain a specified level of performance in cases ofsoftware faults or of infringement of its specified interface. [RD3]
Maintainability:Capability of the software product to be modified. Modifications may include corrections,improvements or adaptation of the software to changes in environment, and in requirementsand functional specifications. [RD3]
Portability:Capability of the software product to be transferred from one environment to another. [RD3]
Reliability:Capability of the software product to maintain a specified level of performance when usedunder specified conditions. [RD3]
Stability:Capability of the software product to avoid unexpected effects from modifications of thesoftware. [RD3]
Testability:Capability of the software product to enable modified software to be validated. [RD3]
EVA-102/01/451Page 10
3. PRESENTATION OF THE RULES
3.1. Organisation of rules
The rules are organised under different topics: (a) File Organisation,(b) Declaration and definition,(c) Function usage,(d) Control flow structuring,(e) Operand usage,(f) Operator usage,(g) Expressions,(h) Code typing,(i) Naming.
3.2. Specification of the rules
Each rule is specified in a dedicated sheet containing the following items.(a) Identifier: the unique identifier of a rule is a 4 character string. The rule identifiers are
used in the evaluation modules (see the Assessment item below)RC - flag programming constructions which may lead to an unintended behaviour of thesoftware. Therefore, each violation is supposed to be deeply examined to state whether ornot it may undermine the reliability of the software.CF - control flow structuring.CM - complexity management.CO - comprehension of source code.CT - code typing.KS - Korn shell.NR - naming of resources.OO - object oriented.PE - Perl script.RU – resource usage.SC – statement complexity.
(b) Title: the title is a short sentence describing the rule.(c) Languages: it indicates the language(s) addressed by the rule. When "ALL" is mentioned,
it means that the rule is applicable to all programming languages. (d) Characteristics: this item lists one or more quality characteristics (see [RD3]) which the
respect of the rule contributes to.(e) Severity: 3 levels of severity or importance of the rule are defined:
(i) "1": mandatory : the violation of the rule significantly undermines the qualitycharacteristics (maintainability, reliability, portability) of the software product; allexceptions to the rule shall be clearly justified using dedicated comments in thecode (see rule CT00).
(ii) "2": recommended: repeated violations of the rule may undermine the qualitycharacteristics (maintainability, reliability, portability) of the software product; onlya few violations are acceptable.
(iii) "3": advisable: respecting the rule contributes to increasing the level of the qualitycharacteristics (maintainability, reliability, portability) of the software product; it is
EVA-102/01/451Page 11
mainly recommended to respect these rules when a high level of quality is requiredfor the software product.
(f) Rationale: this item presents the justification or explanation of the rule;(g) Exception: this item presents cases where the rule could be violated;(h) Example: when relevant, an example is provided with incorrect and/or correct uses of the
rule;(i) Assessment: this item refers to the evaluation module(s) to be used to assess the effective
application of the rule.
3.3. Writing conventions
The intent to generalise some concepts and practices to extent the scope of this document hassometimes led to use "generic" titles, rational and examples in the specification sheet of somerules. For instance, the generic term "function" is used to indifferently designate a C function, a Javamethod, a Fortran routine, a C++ member, a Perl sub., a Pascal procedure, etc. according tothe programming language concerned.
As an example, the rule "CM00: A function shall not have an excessive intrinsic complexity"can have several instances according to the programming language: (a) in C: "CM00: A C function shall not have an excessive intrinsic complexity", (b) in Java: "CM00: A Java method shall not have an excessive intrinsic complexity", (c) in Fortran : "CM00: A Fortran routine shall not have an excessive intrinsic complexity".
Concerning the examples, when a rule is applicable to several programming languages, theexample is generally provided in the most common language (e.g. C).
EVA-102/01/451Page 12
4. SUMMARY OF THE RULES
5.1. File organisation............................................................................................................... 16CO00 - A source file shall not be too long........................................................................... 16CT22 - There shall be a file header. ..................................................................................... 17CO01 - A compilation unit shall follow a standard layout. ................................................. 18CO02 - Duplicating source code shall be avoided. .............................................................. 19CO20 - All declared classes and/or packages shall be used................................................. 20CO20 - A header file shall not contain more than one class declaration. ............................ 21CM01 - A class shall not have an excessive intrinsic complexity. ...................................... 22NR06 - Absolute pathname shall not be used when including files..................................... 24CO10 - A header file shall be prevented from multiple inclusions...................................... 25CT24 - The “#undef” compilation mark shall not be used. ................................................. 26CT25 - The “#” compilation mark shall be in first column. ................................................ 27PE01 - use strict shall be used. ................................................................................... 28PE02 - use warnings shall be used. .............................................................................. 29PE03 - use English shall be used.................................................................................. 30
5.2. Declaration and definition................................................................................................ 31RU19 - Constants shall be represented by symbols. ............................................................ 31KS20 - A constant shall be defined with the key word readonly.................................... 33RU26 - Global resources shall be declared once in a included file...................................... 34RU24 - Every local resource shall be declared static. .................................................. 35PE21 - All sub local variables shall be defined with my...................................................... 36KS21 - The function local variables shall be defined with typeset. ............................... 37OO21 – Fields, methods and classes shall be defined as inaccessible as possible. ............. 38OO22 – Instance fields shall be declared “private”. ............................................................ 39OO23 – Public constants shall be defined in a interface...................................................... 40
5.3. Function usage.................................................................................................................. 41C030 - All declared functions shall be used......................................................................... 41CT23 - There shall be a function header. ............................................................................. 42CO31 - A function shall follow a standard layout. .............................................................. 43CM00 - A function shall not have an excessive intrinsic complexity.................................. 44CT00 - A function must contain enough comments in order to improve its analysability. . 46RU12 - A function shall have a single declaration using prototypes which shall be identicalto the function definition. ..................................................................................................... 47RU11 - Every function shall have an explicit return type.................................................... 48RU22 - The number of parameters passed to a function call shall match the functionprototype............................................................................................................................... 49RU13 - Functions shall not have a variable number of formal parameters.......................... 50KS31 - A function shall validate the number of received arguments. ................................. 51RU31 - A function shall validate input parameters before use. ........................................... 52KS32 - Only POSIX utilities shall be used. ......................................................................... 52
5.4. Control flow structuring ................................................................................................... 54CF00 - Backward branching shall not be used.................................................................... 54CF01 - The continue statement shall not be used. .......................................................... 55KS41 - The "continue n" statement shall not be used. ................................................. 56CF02 - The break statement shall not be used in a loop. .................................................. 57KS42 - The "break n" statement shall not be used. ........................................................ 58
EVA-102/01/451Page 13
CF03 - No statement shall be located after a branching statement or an exit statementwithin a block ....................................................................................................................... 59CF04 - The goto statement shall only be used for exception or error processing. ............ 60CF05 - A function shall have a single exit point.................................................................. 61CF06 - Each case in a switch statement shall be terminated by a break statement....... 62RC01 - No consecutive non empty case clauses shall be executed in sequence.................. 64CF07 - A default case shall always be specified in a switch statement. .......................... 65CF08 - There shall be only a single break statement in each case of a switch statement............................................................................................................................................... 66CF09 - A switch statement shall contain at least one case. .............................................. 68CF17 – All if, else if construct shall contain a final else clause. ........................ 69OO41 - Exceptions shall be used to manage errors. ........................................................... 70OO42 - Catch statements shall not have empty bodies. .................................................... 71
5.5. Operand usage .................................................................................................................. 72RU04 - All declared variables shall be used. ....................................................................... 72RU15 - All formal parameters shall be used. ....................................................................... 73RU00 - All variables shall have been written to before being read. .................................... 74RU30 - A local variable shall always be initialised. ............................................................ 75RU03 - A pointer shall always be initialised........................................................................ 77OO51 – Constructor shall initialise all data members.......................................................... 78OO52 – Static methods and fields shall not be accessed through an object. ....................... 79RC05 - A for statement counter shall not be modified inside the loop. ............................... 80RU06 - Floating point variables shall not be used as loop counters. ................................... 81RU07 - Type casting from any type to or from pointers shall not be used. ......................... 82RC03 - Floating point variables shall not be tested for exact equality or inequality. .......... 83RU10 - The result of a non void function shall always be used........................................... 84KS51 - The IFS internal variable shall not be modified. .................................................... 85KS52 - An internal script function shall be preferred to an external command................... 86KS53- All temporary files shall be deleted as soon as possible........................................... 87KS54 - When a test is made on a character string, it shall take into account the case ofempty string.......................................................................................................................... 88CO51 - All memory allocated shall be freed after used allocation. ..................................... 89
5.6. Operator usage.................................................................................................................. 90SC02 - The ternary operator “?:” shall not be used.............................................................. 90KS61 - The set statement shall not be used to redefine the program arguments............... 91KS62 - The [[...]]notation shall be preferred to the test statement. ......................... 93KS63 - The test abbreviations && and || shall not be used. ............................................... 94KS64 - The eval statement shall not be used..................................................................... 95KS65 - The internal functions let or $(()) shall be preferred to the expr command forarithmetic calculus................................................................................................................ 96
5.7. Expressions....................................................................................................................... 97SC08 – An assignment shall not be embedded within an expression. ................................. 97RC04 – There shall be no assignment at the highest level of a condition............................ 99RC02 - The value of an expression shall be the same under any order of evaluation that thestandard allows. .................................................................................................................. 100RC13 - An expression shall not contain function calls using common effective parametersor resources. ....................................................................................................................... 101RC15 - The effective parameters of a call shall not be correlated expressions. ................ 102SC01 - Multiple assignments shall not be used.................................................................. 103SC03 - The “*” shall not be used to access to a structure field.......................................... 104
EVA-102/01/451Page 14
SC05 - The level of complexity of a reference shall be limited to 4.................................. 105SC06 - Explicit casting shall be used in expression with heterogeneous types. ................ 106OO71 – The “equals()” method shall be used to compare two values of String objects. .. 107SC04 - A condition with more than 4 logical operators shall not contain several distinctoperators. ............................................................................................................................ 108RC10 - Bitwise operations shall not be performed on signed integer types. ..................... 109PE71 - Existence of hash element shall be tested with exists. ................................... 110
5.8. Code typing .................................................................................................................... 111CT00 - A violation of severity 1 rule shall be tagged by a dedicated comment. ............... 111CT05 - The code shall be presented in a homogeneous way. ............................................ 112CT17 - Spacing between operands and operators shall be consistent................................ 114CT02 - A line shall not exceed the column 80. .................................................................. 115CT03 - There shall be no more than one statement per line. ............................................. 116CT04 - There shall be no more than one declaration per line. ........................................... 117CT06 - Each logical block shall be delimited by braces even if it contains no or onestatement............................................................................................................................. 118CT09 - Comments shall not be embedded within statements. ........................................... 120CT26 - Declarations must appear at the beginning of blocks. ........................................... 121CO80 – All headers shall be "Javadoc-like" commented................................................... 122KS81 - A reference to a variable or a call parameter shall always be enclosed in doublequotes ("). ........................................................................................................................... 123CT28 - Parameters in a macro definition shall be enclosed by parentheses. ..................... 124KS82 - Each non elementary regular expression shall be commented. ............................. 125KS83 - Each non standard redirection of command output shall be commented. ............. 126
5.9. Naming ........................................................................................................................... 127CO90 - Identifiers shall be meaningful. ............................................................................. 127CO91 - Identifiers shall conform to homogeneous capitalisation style. ............................ 128CO92 - Keywords shall not be used as an identifiers. ....................................................... 131NR01 - Constant, macro and enum identifiers shall be in uppercase................................. 132NR02 - An identifier shall not begin by a “_”.................................................................... 133NR04 - Two “_” character shall not be used consecutively............................................... 134NR05 - A global variable shall start by a predefined set of characters. ............................. 135NR07 - The “$” character shall not be used....................................................................... 136NR08 - Keywords from the C++ language shall not be used............................................. 137PE90 - sub parameters shall be named explicitly. ........................................................... 138KS91 - Each temporary file shall have an unique name for each script instance. ............. 139KS92 - The signals trapped by trap statement shall be defined by their name rather bytheir digital code................................................................................................................. 140
EVA-102/01/451Page 15
5. PROGRAMMING RULE SPECIFICATION
Write clearly; do not be too clever,
Make it correct before making it faster,
Make it clear before making it faster, and
Do not sacrifice clarity for efficiency.
Kernighan
5.1. File organisation
CO00 - A source file shall not be too long.
LanguagesALL
{{ TC “CO00 - A source file shall not be toolong.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{{ TC “CO00 - A source file shall not be too long.” \f“Maintainability“ \l 9}}
Severity2
{ TC “CO00 - A sourcefile shall not be toolong.” \f “2“ \l 9}
Rationale Files with more than 1000 lines are cumbersome to deal with. The editormay not have enough temp space to edit the file, compilation will gomore slowly, etc.Moreover, limiting the length of a source file encourages thedecomposition of the processing in several compilation units.The decomposition shall follow the design and ensures a maximumcohesion within the compilation unit. Cohesion criteria are commonfunctional processing, common data processing, sequential execution,processing synchronisation, etc.
Exception Longer files are authorised as far as a strong cohesion is targeted.
Example None
Assessment Source code inspection
EVA-102/01/451Page 17
CT22 - There shall be a file header.
LanguagesALL
{{ TC “CT22 - There shall be a file header.” \f“ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CT22 - There shall be a file header.” \f“Maintainability“ \l 9}
Severity2
{ TC “CT22 - Thereshall be a file header.”\f “2“ \l 9}
Rationale The file header is a comment block at the top of a file. It should explainwhat the code in the file does.
Exception None
Example/*========================================================= * File: * Component: *--------------------------------------------------------- * Purpose: * * *--------------------------------------------------------- * Resources used: * * *========================================================= */
Assessment Source code inspection
EVA-102/01/451Page 18
CO01 - A compilation unit shall follow a standard layout.
LanguagesC
{{ TC “CO01 - A compilation unit shall follow astandard layout.” \f “C“ \l 9}}
CharacteristicsMaintainability
{{ TC “CO01 - A compilation unit shall follow a standardlayout.” \f “Maintainability“ \l 9}}
Severity2
{ TC “CO01 - Acompilation unit shallfollow a standardlayout.” \f “2“ \l 9}
Rationale The organisation of information within a file is as important tomaintainability as the organisation of information among files.
Exception None
Example In C language, the organisation of a compilation unit shall be following: A compilation unit is composed of 2 files: (a) a header file: it represents the interface of the compilation unit by
specifying the resources (constant, types, variables, functions,…)visible from the other compilation units or the system; it shall notcontain any declaration of internal resources of the compilation unit;
(b) a source file: it represents the implementation in which are definedthe resources (constant, types, variables, functions,…) of thecompilation unit; a source file shall always include its correspondingheader file.
In a header file, the block of declaration should be sequentially organisedin the following way:(a) system header file includes: #include <...> statements,(b) constant and then function macro definition : #define statements
(using, eventually, common header files includes),(c) type declaration : typedef, enum, etc. statement (using,
eventually, common header files includes),(d) external data declaration (using eventually, common header files
includes),(e) exported functions declaration (without using a header file include),(f) imported types and data declaration (using systematically header file
includes).The source file should be organised according to the above lay out:(a) compilation unit header file include,(b) external used types and functions declaration (using systematically
header file includes),(c) local function declaration (using static allocation attribute),(d) local variables declaration/definition (using static allocation
attribute),(e) local functions definition, (f) main()function definition if the compilation unit is the principal.
Assessment Source code inspection
EVA-102/01/451Page 19
CO02 - Duplicating source code shall be avoided.
LanguagesALL
{{ TC “CO02 - Duplicating source code shall beavoided.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{{ TC “CO02 - Duplicating source code shall be avoided.”\f “Maintainability“ \l 9}}
Severity2
{ TC “CO02 -Duplicating source codeshall be avoided.” \f “2“\l 9}
Rationale Duplicated code (same statements with different or similar operands)uses twice the necessary memory. It could be subject to an incompleteupdate in maintenance phase and requires twice the same tests. According to the case, it is advisable to: (a) create a sub-program including the duplicated code, and to refer to it
several times.(b) include the duplicated code in a loop.
Exception Code may be duplicated:(a) if the similar parts of the code belong to two independent objects with
the same level,(b) for resource behaviour constraints, when, for instance, the code
generated by the sub-program call is much bigger than the duplicatedcode itself,
(c) for time behaviour constraints.
Example None
Assessment Control flow analysisSource code inspection
EVA-102/01/451Page 20
CO20 - All declared classes and/or packages shall be used.
LanguagesC++
{ TC “CO20 - All declared classes and/orpackages shall be used.” \f “+“ \l 9}
Java{{ TC “CO20 - All declared classes and/orpackages shall be used.” \f “Java“ \l 9}}
CharacteristicsMaintainability
{ TC “CO20 - All declared classes and/or packages shall beused.” \f “Maintainability“ \l 9}
Severity2
{ TC “CO20 - Alldeclared classes and/orpackages shall beused.” \f “2“ \l 9}
Rationale Unused resources increase the difficulty of understanding the resourceseffectively used by the code. Keeping only useful declarations improvesthe analysability of the program.Moreover, unused objects unnecessarily increase the memoryrequirements for the software product.
Exception None
Example None
Assessment Source code inspection
EVA-102/01/451Page 21
CO20 - A header file shall not contain more than one class declaration.
LanguagesC++
{{ TC “CO20 - A header file shall not containmore than one class declaration.” \f “+“ \l 9}}
Java{{ TC “CO20 - A header file shall not containmore than one class declaration.” \f “Java“ \l 9}}
CharacteristicsMaintainability
{ TC “CO20 - A header file shall not contain more than oneclass declaration.” \f “Maintainability“ \l 9}
Severity3
{ TC “CO20 - A headerfile shall not containmore than one classdeclaration.” \f “3“ \l 9}
Rationale Having a single class declared in a header file eases configurationmanagement. The name of the file shall be built from the name of the class declared ordefined in this file.
Exception None
Example None
Assessment Programming rule checking
EVA-102/01/451Page 22
CM01 - A class shall not have an excessive intrinsic complexity.
LanguagesJava
{{ TC “CM01 - A class shall not have anexcessive intrinsic complexity.” \f “Java“ \l 9}}
C++{{ TC “CM01 - A class shall not have anexcessive intrinsic complexity.” \f “+“ \l 9}}
CharacteristicsMaintainability
{{ TC “CM01 - A class shall not have an excessive intrinsiccomplexity.” \f “Maintainability“ \l 9}}
Severity1
{ TC “CM01 - A classshall not have anexcessive intrinsiccomplexity.” \f “1“ \l 9}
Rationale Numerous studies have shown that complexity is strongly correlated withtime to detect and fix defects in a source code.The complexity of a class is not only related to its length. Othersattributes have to be taken into account.(a) volume of processing,(b) coupling with others classes,(c) inheritance relationship,(d) interface.
In order to control the intrinsic complexity of a class, at least, half of thefollowing thresholds shall be respected:(a) no more than 7 attributes,(b) no more than 25 methods,(c) no more than 80 control structures in the methods,(d) no more than 5 inherited classes,(e) no more than 7 classes referenced,(f) no more than 75% of non virtual methods,(g) no more than 33% of non private fields.
Indeed, a class with a single "out-of-threshold" attribute can not beconsidered as too complex as far as the other complexity attributes arereasonable.On the opposite, when, at least, half on the above measures exceed theassociated thresholds, the corresponding class is characterised by anexcessive intrinsic complexity:(a) a high number of methods and/or attributes,(b) complex processing,(c) significant inheritance relationship,(d) coupling with numerous classes.
The combination of the above complexity attributes do not contribute tooptimising the maintenance activities of the related software component. Therefore, the level of maintainability shall be considered asunsatisfactory and corrective actions shall be performed on the classes.These actions may include:(a) break-up of processing into several (sub-)classes,(b) encapsulation,(c) factorisation of code,
EVA-102/01/451Page 23
(d) addition of comments, when the software component has criticalconstraints related to some sub-characteristics such as fault toleranceor time behaviour, which sometimes, leads to build softwarecomponents against some of the elementary rules of maintainability.
Exception None
Example None.
Assessment Complexity measurement.
EVA-102/01/451Page 24
NR06 - Absolute pathname shall not be used when including files.
LanguagesC
{{ TC “NR06 - Absolute pathname shall not beused when including files.” \f “C“ \l 9}}
C++{ TC “NR06 - Absolute pathname shall not beused when including files.” \f “+“ \l 9}
CharacteristicsPortability
{ TC “NR06 - Absolute pathname shall not be used whenincluding files.” \f “Portability“ \l 9}
Severity1
{ TC “NR06 - Absolutepathname shall not beused when includingfiles.” \f “1“ \l 9}
Rationale This rule protects the code from modification of the files organisation orcomputer change.
Exception None
Example/* correct */#include <sys/stat.h>#include ”hydro.h”#include <X11/Xlib.h>
Assessment Programming rule checking
EVA-102/01/451Page 25
CO10 - A header file shall be prevented from multiple inclusions.
LanguagesC
{{ TC “CO10 - A header file shall be preventedfrom multiple inclusions.” \f “C“ \l 9}}
C++{ TC “CO10 - A header file shall be preventedfrom multiple inclusions.” \f “+“ \l 9}
CharacteristicsMaintainability
{{ TC “CO10 - A header file shall be prevented frommultiple inclusions.” \f “Maintainability“ \l 9}}
Severity2
{ TC “CO10 - A headerfile shall be preventedfrom multipleinclusions.” \f “2“ \l 9}
Rationale Repeated declarations can happen if header files are nested and willcause the compilation to fail.In order to prevent a header file from multiple inclusions, the file shallstart by a #ifndef compilation mark and end by a #endif compilationmark.The first inclusion of the header file will define a macro statement andeverything else in the file. Subsequent inclusions will skip everythingbetween the #ifndef and #endif compilation marks. Thus, multipleinclusions of the header file will be harmless, except for a minor increasein compilation time.
Exception None.
Example /* correct */#ifndef LOCAL_H#define LOCAL_H...#endif
Assessment Source code inspection
EVA-102/01/451Page 26
CT24 - The “#undef” compilation mark shall not be used.
LanguagesC
{{ TC “CT24 - The “#undef” compilation markshall not be used.” \f “C“ \l 9}}
C++{ TC “CT24 - The “#undef” compilation markshall not be used.” \f “+“ \l 9}
CharacteristicsPortability
{ TC “CT24 - The “#undef” compilation mark shall not beused.” \f “Portability“ \l 9}
Maintainability{ TC “CT24 - The “#undef” compilation mark shall not beused.” \f “Maintainability“ \l 9}
Severity3
{ TC “CT24 - The“#undef” compilationmark shall not be used.”\f “3“ \l 9}
Rationale #undef shall not normally be used. Its use can lead to confusion withrespect to the existence or meaning of a macro when it is used in thecode.
Exception None
Example/* incorrect */#define COUNT(a) (sizeof(a) / sizeof(a[0])...#undef COUNT...#define COUNT 10
Assessment Programming rule checking
EVA-102/01/451Page 27
CT25 - The “#” compilation mark shall be in first column.
LanguagesC
{{ TC “CT25 - The “#” compilation mark shall bein first column.” \f “C“ \l 9}}
CharacteristicsPortability
{ TC “CT25 - The “#” compilation mark shall be in firstcolumn.” \f “Portability“ \l 9}
Severity3
{ TC “CT25 - The “#”compilation mark shallbe in first column.” \f“3“ \l 9}
Rationale Preprocessor directives must always have the # in column 1. Some Cpreprocessors (especially in utility tools) do not fully implement the Cstandard.
Exception None
Example/* incorrect */ if (x) { #define SUN ...; #else ...; #endif }
/* correct */ if (x) {#define SUN ...;#else ...;#endif }
Assessment Programming rule checking
EVA-102/01/451Page 28
PE01 - use strict shall be used.
LanguagesPerl
{{ TC “PE01 - use strict shall be used.” \f “l“ \l 9}}
CharacteristicsReliability
{{ TC “PE01 - use strict shall be used.” \f “Reliability“ \l9}}
Maintainability{{ TC “PE01 - use strict shall be used.” \f “Maintainability“\l 9}}
Portability{{ TC “PE01 - use strict shall be used.” \f “Portability“ \l9}}
Severity2
{ TC “PE01 - use strictshall be used.” \f “2“ \l9}
Rationale use strict enables the Perl interpreter to perform extended checks atcompilation time, in order to pinpoint common pitfalls and to enforce anumber of sound programming practices.
Exception None
Example Noneuse strict;...my $var = foo;# error: Bareword "foo" not allowed
Assessment Source code inspection
EVA-102/01/451Page 29
PE02 - use warnings shall be used.
LanguagesPerl
{{ TC “PE02 - use warnings shall be used.” \f “l“\l 9}}
CharacteristicsReliability
{{ TC “PE02 - use warnings shall be used.” \f “Reliability“\l 9}}
Severity2
{ TC “PE02 - usewarnings shall beused.” \f “2“ \l 9}
Rationale use warnings enables the Perl interpreter to perform extended checksat compilation and execution time. These checks point out potentialproblems and probable oversight of the programmer.
Exception None
Example use warnings;...my $var;while ($var ne “That’s all, folks !”) { # warning : use of # undefined value. ...}
Assessment Source code inspection
EVA-102/01/451Page 30
PE03 - use English shall be used.
LanguagesPerl
{{ TC “PE03 - use English shall be used.” \f “l“ \l9}}
CharacteristicsMaintainability
{{ TC “PE03 - use English shall be used.” \f“Maintainability“ \l 9}}
Severity2
{ TC “PE03 - useEnglish shall be used.”\f “2“ \l 9}
Rationale Perl predefined variables have short names (often consisting of apunctuation mark) which are difficult to read and to remember. TheEnglish module defines human readable aliases for these variables.
Exception None
Example use English;
# Sallow in the whole fileundef $INPUT_RECORD_SEPARATOR;my $content = <>;
# Try calling foobareval { &foobar();}if ($EVAL_ERROR) { # error during foobar ...}
Assessment Source code inspection
EVA-102/01/451Page 31
5.2. Declaration and definition
RU19 - Constants shall be represented by symbols.
LanguagesALL
{{ TC “RU19 - Constants shall be represented bysymbols.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “RU19 - Constants shall be represented by symbols.”\f “Maintainability“ \l 9}
Severity2
{ TC “RU19 -Constants shall berepresented bysymbols.” \f “2“ \l 9}
Rationale Constants shall be represented by symbols the name of which must besignificant; this rule shall especially apply to the sizing of arrays,structures and types.When applicable, the constants, which are used in more than one file,shall be centralised in one header file. See also rule RU26.
Exception An over-perfectionism would lead to represent 0 by ZERO, 1 by ONE,…
Example In C:
/* incorrect */int item_list [10]; /* comment */...
while (item_n < 10){ ...; printf(”ERROR: too many items selected”); ...;}
/* correct */#define MAX_ITEM 10static const char ERR_MSG_5[] = "ERROR: too many items selected" ;
int item_list [MAX_ITEM]; /* comment */...
while (item_n < MAX_ITEM){ ...; /* "ERROR: too many items selected" */ printf(ERR_MSG_5); ...;}
In Java
// incorrectint item_list [10]; // comment...
EVA-102/01/451Page 32
while (item_n < 10){ ...; System.out.println(”ERROR: too many items selected”); ...;}
// correctprivate static final int MAX_ITEM = 10;private static final String ERR_MSG_5 = "ERROR: too many itemsselected";
int item_list [MAX_ITEM]; // comment...
while (item_n < MAX_ITEM){ ...; // "ERROR: too many items selected" System.out.println(ERR_MSG_5); ...;}
In Perl
// incorrectif ($. == 20) { # comment ...}
while ($item_n < 10) { ...; print STDERR ”ERROR: too many items selected”; ...;}
// correctuse English;sub MAX_ITEM { 10 }my $ERR_MSG_5 = "ERROR: too many items selected";
if ($INPUT_LINE_NUMBER == MAX_ITEM) { # comment ...}
while ($item_n < MAX_ITEM) { ...; print STDERR $ERR_MSG_5; ...;}
Assessment Programming rule checking
EVA-102/01/451Page 33
KS20 - A constant shall be defined with the key word readonly.
LanguagesKorn shell
{{ TC “KS20 - A constant shall be defined withthe key word readonly.” \f "Korn shell" \l 9}}
CharacteristicsReliability
{{ TC “KS20 - A constant shall be defined with the keyword readonly.” \f “Reliability“ \l 9}}
Severity2
{ TC “KS20 - Aconstant shall bedefined with the keyword readonly.” \f “2“\l 9}
Rationale By the using the key word readonly when defining a resource, the shellwill intercept all intents to modify the related resource and will generatean error.In Korn shell, it is also possible to use typeset -r.
Exception None
Example The intent to modify pi will fail
#!/bin/ksh# const.sh##readonly pi=3.14159
pi=3
$ const.sh./t0[5]: pi: is read only
Assessment Source code inspection
EVA-102/01/451Page 34
RU26 - Global resources shall be declared once in a included file.
LanguagesC
{{ TC “RU26 - Global resources shall be declaredonce in a included file.” \f “C“ \l 9}}
CharacteristicsMaintainability
{ TC “RU26 - Global resources shall be declared once in aincluded file.” \f “Maintainability“ \l 9}
Severity2
{ TC “RU26 - Globalresources shall bedeclared once in aincluded file.” \f “2“ \l9}
Rationale All global resources shall be grouped together and declared in one ormore header files, which shall be included whenever necessary.Multiple definitions in different files are a problem even if definitions areidentical, and obviously serious if they are different.A single instance of a resource declaration increases the changeability.
Exception None
Example/* incorrect */file1.c:...;#define MAX_ITEM 10
file2.c:...;#define MAX_ITEM 10static const char ERR_MSG_5[] = ”ERROR: too many items selected” ;
file3.c:...;static const char ERR_MSG_5[] = ”ERROR: too many items selected” ;
/* correct */constant.h:...;#define MAX_ITEM 10
error.h:...;static const char ERR_MSG_5[] = ”ERROR: too many items selected” ;
file1.c:...;#include constant.h
file2.c:...;#include constant.h#include error.h
file3.c:#include error.h
Assessment Programming rule checking
EVA-102/01/451Page 35
RU24 - Every local resource shall be declared static.
LanguagesC
{{ TC “RU24 - Every local resource shall bedeclared static.” \f “C“ \l 9}}
CharacteristicsMaintainability
{ TC “RU24 - Every local resource shall be declaredstatic.” \f “Maintainability“ \l 9}
Severity2
{ TC “RU24 - Everylocal resource shall bedeclared static.” \f “2“ \l9}
Rationale Local resources (variables, functions …) used only in a single file shallbe declared static. The static attribute indicates that the visibility ofthe resources is limited to the file. More generally, the storage class attribute shall always be explicitlymentioned when declaring a resource:(a) extern: for the external variables to the compilation unit,(b) static: for the local resources only used in the compilation unit; the
static attribute indicates that the visibility of the resource is limitedto the file.
The register storage-class attribute should not be used.
Declarations at file scope are by default external. Therefore, if two filesboth declare an identifier with the same name at the file scope, the linkerwill either give an error, or they will be the same variable which may notbe what the programmer intended. By systematically defining the attribute, the visibility of the resource isexplicitly indicated and there is no possible omission which may denote alack of consistency.It shall be remind that the static key-word used in the declaration of avariable within a function has not the same meaning. It indicates thepersistency of the variable.
Exception None
Example/* correct */
static void f(void);
Assessment Programming rule checking
EVA-102/01/451Page 36
PE21 - All sub local variables shall be defined with my.
LanguagesPerl
{{ TC “PE21 - All sub local variables shall bedefined with my.” \f “l“ \l 9}}
CharacteristicsReliability
{{ TC “PE21 - All sub local variables shall be defined withmy.” \f “Reliability“ \l 9}}
Severity2
{ TC “PE21 - All sublocal variables shall bedefined with my.” \f “2“\l 9}
Rationale If my is not used to define a variable local to a sub, it is possible toreference, and therefore, modify an other homonymous global variable oran environment variable. The possible side effect may lead to anunintended behaviour.
Exception Predefined global variables cannot be redefined with my: use localinstead.
Example sub fire {
# Parameter asssignmentmy ($stepCount, $stepDuration) = @_;while ($stepCount > 0) {
my $duration = $stepDuration * $stepCount; print "$duration minutes to go\n"; --$stepCount;
} print "Boum!\n";}
for my $elem (@list) { ...}
Assessment Source code inspection
EVA-102/01/451Page 37
KS21 - The function local variables shall be defined with typeset.
LanguagesKorn shell
{{ TC “KS21 - The function local variables shallbe defined with typeset.” \f "Korn shell" \l 9}}
CharacteristicsReliability
{{ TC “KS21 - The function local variables shall be definedwith typeset.” \f “Reliability“ \l 9}}
Severity2
{ TC “KS21 - Thefunction local variablesshall be defined withtypeset.” \f “2“ \l 9}
Rationale If typeset is not used to define a variable, it is possible to reference,and therefore, modify another homonymous global variable or anenvironment variable. The possible side effect may lead to an unintendedbehaviour.
Exception None
Example This function uses count as real local variable
#!/bin/ksh# *** Correct ***#function func1 { # No argument typeset count=0 # Local variable while [[ $count -lt 10 ]] do let count=count+1 done return 0}
Assessment Source code inspection
EVA-102/01/451Page 38
OO21 – Fields, methods and classes shall be defined as inaccessible aspossible.
LanguagesJava
{{ TC “OO21 – Fields, methods and classes shallbe defined as inaccessible as possible.” \f “Java“ \l9}}
C++{ TC “OO21 – Fields, methods and classes shallbe defined as inaccessible as possible.” \f “+“ \l 9}
CharacteristicsMaintainability
{ TC “OO21 – Fields, methods and classes shall be definedas inaccessible as possible.” \f “Maintainability“ \l 9}
Severity2
{ TC “OO21 – Fields,methods and classesshall be defined asinaccessible aspossible.” \f “2“ \l 9}
Rationale Fields, methods and classes visibility shall be defined as inaccessible aspossible according to where they are used.Thus, the code respects data encapsulation. The code dependencies areeasier to understand.The different cases are:(a) if a non-static field is declared public or protected or without access
modifier and is used only in the class which declares it, it must bedeclared private.
(b) if a method is declared public and is used only in the package whichdeclares it, it must be declared without access modifier.
(c) if a method is declared protected or without access modifier and isused only in the class which declares it, it must be declared private.
(d) if a class is declared public and is used only in the package containingit , it must be declared non-public (without access modifier).
In C++, the above cases shall be adapted. For instance, the concept ofpackages does not exist.
Exception None
Example class A { int size; // no other class uses it, should be private public void calcul() { return size*12;
}}
Assessment Source code inspection
EVA-102/01/451Page 39
OO22 – Instance fields shall be declared “private”.
LanguagesJava
{{ TC “OO22 – Instance fields shall be declared“private”.” \f “Java“ \l 9}}
C++{ TC “OO22 – Instance fields shall be declared“private”.” \f “+“ \l 9}
CharacteristicsMaintainability
{ TC “OO22 – Instance fields shall be declared “private”.”\f “Maintainability“ \l 9}
Severity2
{ TC “OO22 – Instancefields shall be declared“private”.” \f “2“ \l 9}
Rationale Instances fields are an implementation detail of the class. It is a goodpractice to hide such implementation details from users of this class.Instead, provide the user with methods to access and/or change suchfields.
Exception None.
Example // incorrectclass A {
private int a;protected double b; // violation
}
// correctclass A {
private int a;private double price;
// access methodsprotected getPrice() {
return price;}protected void setPrice(double p) {
price = p;}
}.
Assessment Programming rule checking.
EVA-102/01/451Page 40
OO23 – Public constants shall be defined in a interface.
LanguagesJava
{{ TC “OO23 – Public constants shall be definedin a interface.” \f “Java“ \l 9}}
CharacteristicsMaintainability
{ TC “OO23 – Public constants shall be defined in ainterface.” \f “Maintainability“ \l 9}
Severity2
{ TC “OO23 – Publicconstants shall bedefined in a interface.”\f “2“ \l 9}
Rationale Public constants which are used in more than one class, shall becentralised in one interface. A constant used only in one class must be private, and a public constantused in more than one class must be defined once a time in an interface,the class using it must implement this interface.In case of future modification of the constant value, there is no risk toforget to transfer the modification to all occurrences.
Exception None
Example// incorrectclass A {
public static final int ARRAY_SIZE = 1000;
}
// correctinterface Constants {
public static final int ARRAY_SIZE = 1000;}class A implements Constants {}
Assessment Programming rule checking
EVA-102/01/451Page 41
5.3. Function usage
C030 - All declared functions shall be used.
LanguagesALL
{{ TC “C030 - All declared functions shall beused.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “C030 - All declared functions shall be used.” \f“Maintainability“ \l 9}
Severity1
{ TC “C030 - Alldeclared functions shallbe used.” \f “1“ \l 9}
Rationale Unused resources increase the difficulty of understanding the resourceseffectively used by the code. Keeping only useful declarations improvesthe analysability of the program.Moreover, unused objects unnecessarily increase the memoryrequirements for the software product.
Exception None
Example None
Assessment Programming rule checking
EVA-102/01/451Page 42
CT23 - There shall be a function header.
LanguagesALL
{{ TC “CT23 - There shall be a function header.”\f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CT23 - There shall be a function header.” \f“Maintainability“ \l 9}
Severity3
{ TC “CT23 - Thereshall be a functionheader.” \f “3“ \l 9}
Rationale The function header is a comment block at the top of a function. It shouldexplain what the code in the function does.See also rule CO85.
Exception Low complexity functions (1 statement function or less than 5 statementsfunction with no parameter) are easy to analyse “at a glance” andtherefore may not need a header.
Example /*-------------------------------------------------------- int foo(int age)* Purpose: ... * * @requirement * *--------------------------------------------------------- * * @syntax foo(age) * @param age captain's age * @return captain's foo * *--------------------------------------------------------- */
Assessment Code inspection
EVA-102/01/451Page 43
CO31 - A function shall follow a standard layout.
LanguagesALL
{{ TC “CO31 - A function shall follow a standardlayout.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{{ TC “CO31 - A function shall follow a standard layout.”\f “Maintainability“ \l 9}}
Severity2
{ TC “CO31 - Afunction shall follow astandard layout.” \f “2“\l 9}
Rationale A consistent and standardised organisation within a function allows thereader to easily locate the various blocks of information.
Exception None
Example In C language, the function should be organised according to the abovelay out:(a) function prototype, (b) external variable declaration,(c) local variable declaration,(d) executable statement blocks.
Parameters should be declared in the following order in the functionprototype:(a) "Input" parameters,(b) "Output" parameters,(c) "Input/output" parameters,(d) "Return" code parameters.
Assessment Source code inspection
EVA-102/01/451Page 44
CM00 - A function shall not have an excessive intrinsic complexity.
LanguagesALL
{{ TC “CM00 - A function shall not have anexcessive intrinsic complexity.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{{ TC “CM00 - A function shall not have an excessiveintrinsic complexity.” \f “Maintainability“ \l 9}}
Severity1
{ TC “CM00 - Afunction shall not havean excessive intrinsiccomplexity.” \f “1“ \l 9}
Rationale Numerous studies have shown that complexity is strongly correlated withtime to detect and fix defects in a source code.The complexity of a function is not only related to its length. Othersattributes have to be taken into account:(a) syntactic elements : number of statements, ...,(b) textual elements : average size of statements, ...,(c) control flow : number of paths, maximum nesting level, …,(d) data flow : number of parameters, number of local variables, …, (e) call relationship : number of called functions, ...
In order to control the intrinsic complexity of a function, at least, half ofthe following thresholds shall be respected: (a) no more than 50 statements,(b) no more than 5 formal parameters, (c) no more than 7 local variables,(d) no more than 10 control structures (i.e. cyclomatic number),(e) no more than 5 nesting level,(f) no more than 7 called functions,(g) no more than an average of 9 textual elements per statement.
Indeed, a function with a single "out-of-threshold" attribute can not beconsidered as too complex as far as the other complexity attributes arereasonable. On the opposite, when, at least, half on the above measures exceed theassociated thresholds, the corresponding function is characterised by anexcessive intrinsic complexity:(a) a high number of parameters and/or local variables used,(b) a consequent chaining and/or nesting of control structures,(c) complex and/or repeated statements,(d) numerous calling relationships.
The combination of the above complexity attributes do not contribute tooptimising the maintenance activities of the related software component. Therefore, the level of maintainability shall be considered asunsatisfactory and corrective actions shall be performed on the functions.These actions may include:(a) factorisation of code,(b) break-up of processing into several sub functions,
EVA-102/01/451Page 45
(c) addition of comments, when the software component has criticalconstraints related to some sub-characteristics such as fault toleranceor time behaviour, which sometimes, leads to build softwarecomponents against some of the elementary rules of maintainability.
Exception Functions containing large switch or repetitive structures may seem tohave a high intrinsic complexity according to the attributes listed abovebut being easy to maintain.
Example None
Assessment Complexity measurement
EVA-102/01/451Page 46
CT00 - A function must contain enough comments in order to improve itsanalysability.
LanguagesALL
{{ TC “CT00 - A function must contain enoughcomments in order to improve its analysability.” \f“ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CT00 - A function must contain enough commentsin order to improve its analysability.” \f “Maintainability“\l 9}
Severity1
{ TC “CT00 - Afunction must containenough comments inorder to improve itsanalysability.” \f “1“ \l9}
Rationale People in charge of maintenance activities knows that the analysability ofthe source code is strongly connected to the proportion of comments inthe source code.Comments shall be located at strategic points in the code: (a) to introduce the functional purpose of a large processing,(b) before an important decision point of the control flow,(c) at any critical point of the implementation (without embedded the
code and the comments (see rule CT09),(d) when implementing an infinite loop, (e) at the end of a large processing.The comments shall not paraphrase the code but mainly insist on thefunctional purpose of the code (the "what" ) rather than the explainingthe implementation (the "how").It is also recommended to describe the variables at their declaration ordefinition.A ratio of 1 comment per 5 statements shall be considered as a minimum.This ratio shall be increased for complex functions (more than 50statements).
Exception Some very simple functions (a single statement) do not require anycomment to help maintainers to understand their purpose as far as thename of the function is relevant.
Example None
Assessment Self-descriptiveness measurement
EVA-102/01/451Page 47
RU12 - A function shall have a single declaration using prototypes whichshall be identical to the function definition.
LanguagesC
{{ TC “RU12 - A function shall have a single decusing prototypes which shall be identical to the fdefinition.” \f “C“ \l 9}}
CharacteristicsPortability
{ TC “RU12 - A function shall have a single declaratioprototypes which shall be identical to the function definit“Portability“ \l 9}
Severity1
{ TC “RU12 - A functiohave a single declarationprototypes which shaidentical to the fdefinition.” \f “1“ \l 9}
Rationale A large percentage of all statically detectable faults in C code could beprevented by proper use of the function prototype mechanism. The use ofprototype enables the compiler to check the integrity of functionsdefinitions and calls.Without prototypes, the compiler is not obliged to pick up certain errorsin function calls (e.g. different number of arguments from the functionbody, mismatch in types of arguments between call and definition).This rule implies the following:(a) functions shall always have a prototype declaration and the prototype
shall be visible at both the function definition and call; (b) for each function parameter, the type and identifier name given in the
declaration and definition shall be identical, and the return types shallalso be identical;
(c) every function shall have an explicit return type; that type beingvoid if the function does not return any data (see rule RU11);
(d) functions with no parameters shall be declared with parameter typevoid.
Caution: declarations of the same function with and without prototypesmust be avoided. The implicit conversion of parameters is performeddifferently!
Exception In case of high maintainability constraints, identifiers of parameters maynot be given in prototype. In such case, none of the parameters shall havean identifier.
Example/* incorrect */extern f(); /* unspecified number of parameters */
/* Identifiers of the parameters are missing */extern int g(const char, unsigned short, float);
/* correct */extern int g(const char *name, unsigned short age, float size);
static void h(void);
Assessment Programming rule checking
EVA-102/01/451Page 48
RU11 - Every function shall have an explicit return type.
LanguagesC
{{ TC “RU11 - Every function shall have anexplicit return type.” \f “C“ \l 9}}
CharacteristicsMaintainability
{ TC “RU11 - Every function shall have an explicit returntype.” \f “Maintainability“ \l 9}
Severity1
{ TC “RU11 - Everyfunction shall have anexplicit return type.” \f“1“ \l 9}
Rationale Functions shall always be declared with a return type, that type beingvoid if the function does not return any data.
Exception None
Example/* correct */
extern void f(int);
extern int g(void);
static char *h(const void*);
Assessment Programming rule checking
EVA-102/01/451Page 49
RU22 - The number of parameters passed to a function call shall match thefunction prototype.
LanguagesC
{{ TC “RU22 - The number of parameters passedto a function call shall match the functionprototype.” \f “C“ \l 9}}
CharacteristicsReliability
{ TC “RU22 - The number of parameters passed to afunction call shall match the function prototype.” \f“Reliability“ \l 9}
Portability{ TC “RU22 - The number of parameters passed to afunction call shall match the function prototype.” \f“Portability“ \l 9}
Severity1
{ TC “RU22 - Thenumber of parameterspassed to a function callshall match the functionprototype.” \f “1“ \l 9}
Rationale The function call shall comply with the function prototype in terms ofnumber of parameters and their types.
Exception None
Example/* incorrect */static void f(float);...;int i;g(i);
/* correct */
extern void g(int, const char*);
g(3, “hello !”);
Assessment Programming rule checking
EVA-102/01/451Page 50
RU13 - Functions shall not have a variable number of formal parameters.
LanguagesC
{{ TC “RU13 - Functions shall not have a variablenumber of formal parameters.” \f “C“ \l 9}}
CharacteristicsMaintainability
{ TC “RU13 - Functions shall not have a variable numberof formal parameters.” \f “Maintainability“ \l 9}
Severity2
{ TC “RU13 -Functions shall not havea variable number offormal parameters.” \f“2“ \l 9}
Rationale There are a lot of potential problems with this feature and it shall not beused. It is better to design an interface that uses a fixed number ofarguments, for example with an array or a list.This precludes the use of stdarg.h, va_arg, va_start and va_end,and the ellipsis notation in function prototypes.
Exception None
Example None
Assessment Programming rule checking
EVA-102/01/451Page 51
KS31 - A function shall validate the number of received arguments.
LanguagesKorn shell
{{ TC “KS31 - A function shall validate thenumber of received arguments.” \f "Korn shell" \l9}}
CharacteristicsReliability
{{ TC “KS31 - A function shall validate the number ofreceived arguments.” \f “Reliability“ \l 9}}
Severity2
{ TC “KS31 - Afunction shall validatethe number of receivedarguments.” \f “2“ \l 9}
Rationale Scripts are interpreted not compiled. So a transmittal error such as ainsufficient number of arguments will only be detected when accessing tothe missing argument. If several actions have already being performed, itcan be difficult to restore the initial context.
Exception None
Example In Korn shell
# all functions shall start by a test such as the following
my_function () { # Three arguments if [[ $# -ne 3 ]] then print 'Error' exit $argcount_error_code fi ...}
Assessment Source code inspection
EVA-102/01/451Page 52
RC31 - A function shall validate input parameters before use.
LanguagesALL
{{ TC “RC31 - A function shall validate inputparameters before use.” \f "ALL" \l 9}}
CharacteristicsReliability
{{ TC “RC31 - A function shall validate input parametersbefore use.” \f “Reliability“ \l 9}}
Severity1
{ TC “RC31 - Afunction shall validateinput parameters beforeuse.” \f “1“ \l 9}
Rationale Parameters that contain inappropriate values can cause errors and alsoconstitute a potential security threat by allowing an improper extensionof functionality. Therefore, the following conditions shall be checkedwhenever possible:
(a) Input parameters shall not exceed buffer lengths;(b) Input parameters shall not contain executable code (but can point to
it);(c) Input parameters shall only contain values in the valid range for that
parameter.
The parameter should be corrected or discarded if any of the conditionsabove are not met.This rule shall also apply to any other form of external input (e.g.environment variables, files etc.).
Exception In the case of internal functions where the parameters have already beenvalidated by the calling function, this rule does not apply. An internalfunction is a function that cannot be called from outside the application.
Example For example, assume that a function contains the following selectstatement:SELECT firstname, surname FROM users WHERE surname=<String>.If String is set directly from an input parameter, and the input parameteris set to ‘Amann OR 1=1’, then all values of firstname in the table shallbe returned.
Assessment Source code inspection
EVA-102/01/451Page 53
KS32 - Only POSIX utilities shall be used.
LanguagesKorn shell
{{ TC “KS32 - Only POSIX utilities shall beused.” \f "Korn shell" \l 9}}
CharacteristicsPortability
{{ TC “KS32 - Only POSIX utilities shall be used.” \f“Portability“ \l 9}}
Severity2
{ TC “KS32 - OnlyPOSIX utilities shall beused.” \f “2“ \l 9}
Rationale An intent of POSIX is to normalise the behaviour of utilities. Therefore,using only POSIX utilities improves the adaptability of the script byensuring their availability on the machine used as well as the consistencyof their behaviour. The list of POSIX utilities is the following:
awk, basename, bc, cat, cd, chgrp, chmod, chown, cksum,cmp, comm, command, cp, cut, date, dd, diff, dirname, echo,ed, env, expr, false, find, fold, getconf, getopts, grep,head, id, join, kill, ln, locale, localedef, logger,logname, lp, ls, mailx, mkdir, mkfifo, mv, nohup, od,paste, pathchk, pax, pr, printf, pwd, read, rm, rmdir, sed,sh, sleep, sort, stty, tail, tee, test, touch, tr, true,tty, umask, uname, uniq, wait, wc, xargs.
Exception Non POSIX utilities can be used in case of access to administrationcommands.
Example None
Assessment Source code inspection
EVA-102/01/451Page 54
5.4. Control flow structuring
CF00 - Backward branching shall not be used.
LanguagesALL
{{ TC “CF00 - Backward branching shall not beused.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CF00 - Backward branching shall not be used.” \f“Maintainability“ \l 9}
Severity1
{ TC “CF00 -Backward branchingshall not be used.” \f“1“ \l 9}
Rationale The use of unconditional branching (e.g. goto statement) is nevernecessary (structured programming). The actual condition of iteration of an implied loop created by abackward branching (i.e. to a label located above in the file) are alwaysdifficult to analyse. In addition, a backward branching creates a risk ofinfinite loop. A loop statement (e.g. for, while) should be usedinstead.This rule does not only apply to the only goto statement. According tothe language, it also addresses other branching statement using a label.For instance, in Java, this is the case for the continue or breakstatements (see the example below.)See also rule CF04 for allowed uses of goto statement.
Exception None
Example// In Java// incorrect labfor: for (i = 0; i < N; i++){ if (array[i] < 0) // skip negative item { continue labfor; } // positive items processing ...}
Assessment Control flow analysis
EVA-102/01/451Page 55
CF01 - The continue statement shall not be used.
LanguagesC
{{ TC “CF01 - The continue statement shall not beused.” \f “C“ \l 9}}
C++{ TC “CF01 - The continue statement shall not beused.” \f “+“ \l 9}
Java{{ TC “CF01 - The continue statement shall not beused.” \f “Java“ \l 9}}
CharacteristicsMaintainability
{{ TC “CF01 - The continue statement shall not be used.” \f“Maintainability“ \l 9}}
Severity2
{ TC “CF01 - Thecontinue statement shallnot be used.” \f “2“ \l 9}
Rationale The use of the continue statement without or with label is equivalent toa goto statement.It often hides the actual conditions of processing.
Exception None
Example// incorrectfor (i = 0; i < N; i++){ if (array[i] < 0) // skip negative items { continue; } // positive items processing ...}
// correctfor (i = 0; i < N; i++){ if (array[i] >= 0) { // positive items processing ... }}
Assessment Programming rule checking.
EVA-102/01/451Page 56
KS41 - The "continue n" statement shall not be used.
LanguagesKorn shell
{{ TC “KS41 - The "continue n" statement shallnot be used.” \f "Korn shell" \l 9}}
CharacteristicsMaintainability
{{ TC “KS41 - The "continue n" statement shall not beused.” \f “Maintainability“ \l 9}}
Severity1
{ TC “KS41 - The"continue n" statementshall not be used.” \f“1“ \l 9}
Rationale The continue <n> statement allows to exit from n levels of structure. Therefore, as a branching statement, its use undermines the analysabilityof the code and, above all, its stability when intermediate levels areadded.
Exception None
Example None
Assessment Source code inspection
EVA-102/01/451Page 57
CF02 - The break statement shall not be used in a loop.
LanguagesC
{{ TC “CF02 - The break statement shall not beused in a loop.” \f “C“ \l 9}}
C++{ TC “CF02 - The break statement shall not beused in a loop.” \f “+“ \l 9}
Java{{ TC “CF02 - The break statement shall not beused in a loop.” \f “Java“ \l 9}}
CharacteristicsMaintainability
{{ TC “CF02 - The break statement shall not be used in aloop.” \f “Maintainability“ \l 9}}
Severity3
{ TC “CF02 - The breakstatement shall not beused in a loop.” \f “3“ \l9}
Rationale Having a single exit point improves the analysability of the loopstructures. This feature may allow to debug easily the code (for instance,by setting breakpoints at the structure exit point).The use of the break statement without or with label is equivalent to agoto statement by creating an additional exit point to the loop structure.
Exception None
Example/* incorrect */i = 0;for (i = 0; i < MAX; i++){if (letter[i] == KEY) { break; } ...;}
/* correct */i = 0;while ((i < MAX) && (letter[i] != KEY)){ ...; i++;}
Assessment Programming rule checking
EVA-102/01/451Page 58
KS42 - The "break n" statement shall not be used.
LanguagesKorn shell
{{ TC “KS42 - The "break n" statement shall notbe used.” \f "Korn shell" \l 9}}
CharacteristicsMaintainability
{{ TC “KS42 - The "break n" statement shall not be used.”\f “Maintainability“ \l 9}}
Severity2
{ TC “KS42 - The"break n" statementshall not be used.” \f“2“ \l 9}
Rationale The break <n> statement allows to exit from n levels of structure. Therefore, as a branching statement, its use undermines the analysabilityof the code and, above all, its stability when intermediate levels areadded.
Exception None
Example None
Assessment Source code inspection
EVA-102/01/451Page 59
CF03 - No statement shall be located after a branching statement or an exitstatement within a block
LanguagesALL
{{ TC “CF03 - No statement shall be located aftera branching statement or an exit statement within ablock” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CF03 - No statement shall be located after abranching statement or an exit statement within a block” \f“Maintainability“ \l 9}
Severity1
{ TC “CF03 - Nostatement shall belocated after abranching statement oran exit statement withina block” \f “1“ \l 9}
Rationale Executable statements located after an unconditional branching or an exitpoint within the block cannot under any circumstances be reached. Thisunreachable code increases uselessly the complexity of programs, andshall therefore be avoided.In C, C++, Java or Korn-Shell, branching statements are goto,continue and break. In Perl, other branching statements are last, next statements. In most languages, the exit statement is return.
Exception An unreachable break statement at the end of a switch clause (see ruleCF06).
Example/* incorrect */...; return ConvertToEuros(amount); /* amounts computed in euros */
/* conversion to local currency */ switch (country) { case FRANCE: ...; break; case ITALY: ...; break; case ... } return amount;}
/* correct */ ...; return ConvertToEuros(amount); /* amounts computed in euros */}
Assessment Programming rule checking
EVA-102/01/451Page 60
CF04 - The goto statement shall only be used for exception or errorprocessing.
LanguagesALL
{{ TC “CF04 - The goto statement shall only beused for exception or error processing.” \f “ALL“\l 9}}
CharacteristicsMaintainability
{ TC “CF04 - The goto statement shall only be used forexception or error processing.” \f “Maintainability“ \l 9}
Severity2
{ TC “CF04 - The gotostatement shall only beused for exception orerror processing.” \f “2“\l 9}
Rationale The use of goto statement is never necessary (structured programming).
The use of goto statement must be limited to exception or errorprocessing.
Exception None
Example/* allowed use */while (condition1){ ...; if (condition2) { goto error; } ...;}...;/* error processing */error:...;
Assessment Programming rule checkingSource code inspection
EVA-102/01/451Page 61
CF05 - A function shall have a single exit point.
LanguagesALL
{{ TC “CF05 - A function shall have a single exitpoint.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CF05 - A function shall have a single exit point.” \f“Maintainability“ \l 9}
Severity3
{ TC “CF05 - Afunction shall have asingle exit point.” \f “3“\l 9}
Rationale Structured Programming recommends to have only one entry point andone exit point to each software components.Therefore, a function shall contain a single exit point (i.e. returnstatement). It shall be the last instruction of the function.
Exception Auxiliary exit points used for error handling or in "pre-condition" testingat the beginning of a function does not undermine the analysability thecode. However, their use shall be consistent.
Example None
Assessment Programming rule checking
EVA-102/01/451Page 62
CF06 - Each case in a switch statement shall be terminated by a breakstatement.
LanguagesC
{{ TC “CF06 - Each case in a switch statementshall be terminated by a break statement.” \f “C“ \l9}}
C++{ TC “CF06 - Each case in a switch statementshall be terminated by a break statement.” \f “+“ \l9}
Java{{ TC “CF06 - Each case in a switch statementshall be terminated by a break statement.” \f“Java“ \l 9}}
CharacteristicsMaintainability
{ TC “CF06 - Each case in a switch statement shall beterminated by a break statement.” \f “Maintainability“ \l 9}
Reliability{ TC “CF06 - Each case in a switch statement shall beterminated by a break statement.” \f “Reliability“ \l 9}
Severity2
{ TC “CF06 - Each casein a switch statementshall be terminated by abreak statement.” \f “2“\l 9}
Rationale The behaviour of a switch statement is potentially confusing, becauseeach case when executed will fall through to the code of the next case.The use of a break statement at the end of the clause allows to executeonly the code of that clause. In addition, the last statement of the last clause shall be a breakstatement to avoid forgetting a break when another case statement isadded.See also rules RC01 and CF08.
Exception When the fall-through feature of the switch statement is what isintended (i.e. when there is no break between a code segment and thenext case statement), there shall be a comment where the break wouldnormally be expected. This makes it clear to the reader that this fall-through was intentional.
Exampleswitch (sex){case MALE: ...; break;case FEMALE: ...; break;default: /* Data base integrity has been altered */...; break;}
Or
switch (sex){case MALE:...;/* FALL-THROUGH */
EVA-102/01/451Page 63
case FEMALE: ...; break;default: /* Alien ? */...; break;}
Assessment Programming rule checking
EVA-102/01/451Page 64
RC01 - No consecutive non empty case clauses shall be executed insequence.
LanguagesC
{{ TC “RC01 - No consecutive non empty caseclauses shall be executed in sequence.” \f “C“ \l9}}
C++{ TC “RC01 - No consecutive non empty caseclauses shall be executed in sequence.” \f “+“ \l 9}
Java{{ TC “RC01 - No consecutive non empty caseclauses shall be executed in sequence.” \f “Java“ \l9}}
CharacteristicsReliability
{ TC “RC01 - No consecutive non empty case clauses shallbe executed in sequence.” \f “Reliability“ \l 9}
Severity1
{ TC “RC01 - Noconsecutive non emptycase clauses shall beexecuted in sequence.”\f “1“ \l 9}
Rationale Falling through the next case clause of the switch statement may benot intended and due to a missing break in the previous case. This rule is a refinement of rule CF06.
Exception When the fall-through feature of the switch statement is what isintended (i.e. when there is no break between a code segment and thenext case statement), there shall be a comment where the break wouldnormally be expected. This makes it clear to the reader that this fall-through was intentional.
Example/* incorrect */switch (sex){case MALE: ...; case FEMALE: ...; break;default: /* Data base integrity has been altered */...; break;}
Assessment Programming rule checkingControl flow analysis
EVA-102/01/451Page 65
CF07 - A default case shall always be specified in a switch statement.
LanguagesC
{{ TC “CF07 - A default case shall always bespecified in a switch statement.” \f “C“ \l 9}}
C++{{ TC “CF07 - A default case shall always bespecified in a switch statement.” \f “+“ \l 9}}
Java{{ TC “CF07 - A default case shall always bespecified in a switch statement.” \f “Java“ \l 9}}
CharacteristicsMaintainability
{ TC “CF07 - A default case shall always be specified in aswitch statement.” \f “Maintainability“ \l 9}
Reliability{ TC “CF07 - A default case shall always be specified in aswitch statement.” \f “Reliability“ \l 9}
Severity1
{ TC “CF07 - A defaultcase shall always bespecified in a switchstatement.” \f “1“ \l 9}
Rationale The requirement for a final default clause is fault tolerantprogramming (handles unexpected cases). This clause should takeappropriate actions or contain a suitable comment as to why no action istaken.Moreover the default clause protects the program against a futurechange of the domain of the Assessment expression.The default clause shall appear last in of the switch statement.
Exception None
Exampleswitch (sex){case MALE: ...; break;case FEMALE: ...; break;default: /* Data base integrity has been altered */ error_flag = 1; break;}
Assessment Programming rule checking
EVA-102/01/451Page 66
CF08 - There shall be only a single break statement in each case of aswitch statement.
LanguagesC
{{ TC “CF08 - There shall be only a single breakstatement in each case of a switch statement.” \f“C“ \l 9}}
C++{ TC “CF08 - There shall be only a single breakstatement in each case of a switch statement.” \f“+“ \l 9}
Java{{ TC “CF08 - There shall be only a single breakstatement in each case of a switch statement.” \f“Java“ \l 9}}
CharacteristicsMaintainability
{ TC “CF08 - There shall be only a single break statementin each case of a switch statement.” \f “Maintainability“ \l9}
Severity3
{ TC “CF08 - Thereshall be only a singlebreak statement in eachcase of a switchstatement.” \f “3“ \l 9}
Rationale Having a single exit point improves the analysability. This feature may permit easy debugging (to set breakpoints at the exitpoint for example).
Exception None
Example/* incorrect */
switch (colour){case RED: ...; break;case GREEN: ...; if (condition) { statement_1; break; } statement_2; break;default: /* Others colours: do nothing */ break;}
/* correct version, next page */
EVA-102/01/451Page 67
/* correct */
switch (colour){case RED: ...; break;case GREEN: ...; if (condition) { statement_1; } else { statement_2; } break;default: /* Others colours: do nothing */ break;}
Assessment Programming rule checking
EVA-102/01/451Page 68
CF09 - A switch statement shall contain at least one case.
LanguagesC
{{ TC “CF09 - A switch statement shall contain atleast one case.” \f “C“ \l 9}}
C++{ TC “CF09 - A switch statement shall contain atleast one case.” \f “+“ \l 9}
Java{{ TC “CF09 - A switch statement shall contain atleast one case.” \f “Java“ \l 9}}
CharacteristicsMaintainability
{ TC “CF09 - A switch statement shall contain at least onecase.” \f “Maintainability“ \l 9}
Severity1
{ TC “CF09 - A switchstatement shall containat least one case.” \f “1“\l 9}
Rationale A switch statement without a case clause is so useless that it is probablyan error.
Exception None
Example/* incorrect */switch (condition){ /* dead code */ ...;}
Assessment C programming rule checking
EVA-102/01/451Page 69
CF17 – All if, else if construct shall contain a final else clause.
LanguagesALL
{{ TC “CF17 – All if, else if construct shallcontain a final else clause.” \f “ALL“ \l 9}}
CharacteristicsReliability
{ TC “CF17 – All if, else if construct shall contain a finalelse clause.” \f “Reliability“ \l 9}
Severity2
{ TC “CF17 – All if,else if construct shallcontain a final elseclause.” \f “2“ \l 9}
Rationale Whenever an if statement is followed by one or more else ifstatement, the requirement for a final else clause is fault toleranceprogramming. The else statement should either take appropriate actionor contain a suitable comment as to why no action is taken. This rule
Exception When only a small percentage of clauses have empty bodies or whentheses clauses must contain a dedicated comment.
Example// incorrectif (v == val1) {
// statements 1}else if (v == val2) {
// statements 2}else if (v == val3) {
// statements 3}
// correctif (v == val1) {
// statements 1}else if (v == val2) {
// statements 2}else if (v == val3) {
// statements 3}else {
// default statements}
Assessment Programming rule checking
EVA-102/01/451Page 70
OO41 - Exceptions shall be used to manage errors.
LanguagesALL
{{ TC “OO41 - Exceptions shall be used tomanage errors.” \f “ALL“ \l 9}}
CharacteristicsReliability
{{ TC “OO41 - Exceptions shall be used to manageerrors.” \f “Reliability“ \l 9}}
Maintainability{{ TC “OO41 - Exceptions shall be used to manageerrors.” \f “Maintainability“ \l 9}}
Severity2
{ TC “OO41 -Exceptions shall beused to manage errors.”\f “2“ \l 9}
Rationale When available in the programming language, the exception mechanismshall be used for the centralisation of error recovery.Perl provides exceptions via the eval and die statements.
Exception None
Example In Perl
use English;
# Sallow in the whole fileundef $INPUT_RECORD_SEPARATOR;my $content = <>;
# Try calling foobareval { &foobar();}if ($EVAL_ERROR) { # error during foobar ...}sub foobar { ...; die “internal error”; ...;}
Assessment
EVA-102/01/451Page 71
OO42 - Catch statements shall not have empty bodies.
LanguagesJava
{{ TC “OO42 - Catch statements shall not haveempty bodies.” \f “Java“ \l 9}}
C++{{ TC “OO42 - Catch statements shall not haveempty bodies.” \f “+“ \l 9}}
CharacteristicsReliability
{ TC “OO42 - Catch statements shall not have emptybodies.” \f “Reliability“ \l 9}
Severity1
{ TC “OO42 - Catchstatements shall nothave empty bodies.” \f“1“ \l 9}
Rationale Catch statements should contain error handling code corresponding toexceptions “catched”.In all case, it would be wise to comment or display a message related tothe exception raised.
Exception None.
Example None.
Assessment Programming rule checkingSource code inspection
EVA-102/01/451Page 72
5.5. Operand usage
RU04 - All declared variables shall be used.
LanguagesALL
{{ TC “RU04 - All declared variables shall beused.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “RU04 - All declared variables shall be used.” \f“Maintainability“ \l 9}
Severity1
{ TC “RU04 - Alldeclared variables shallbe used.” \f “1“ \l 9}
Rationale Unused variables, fields or attributes increase the difficulty ofunderstanding the resources effectively used by the code. Keeping onlyuseful declarations improves the analysability of the program.Moreover, unused variables unnecessarily increase the memoryrequirements for the software product.This rule does not only apply to local variables but also to fields orattributes (for instance in a Java class).
Exception None
Example None
Assessment Programming rule checking
EVA-102/01/451Page 73
RU15 - All formal parameters shall be used.
LanguagesALL
{{ TC “RU15 - All formal parameters shall beused.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “RU15 - All formal parameters shall be used.” \f“Maintainability“ \l 9}
Severity2
{ TC “RU15 - Allformal parameters shallbe used.” \f “2“ \l 9}
Rationale Unused parameters increase the difficulty of understanding the resourcesused by the code. Keeping only useful declarations improves theanalysability of the program.
Exception Some frameworks (for example the X Window System toolkit or Motif)impose the formal parameters for callback functions. In these functions,some parameters may be unused by the processing.
Example None
Assessment Programming rule checking
EVA-102/01/451Page 74
RU00 - All variables shall have been written to before being read.
LanguagesALL
{{ TC “RU00 - All variables shall have beenwritten to before being read.” \f “ALL“ \l 9}}
CharacteristicsReliability
{ TC “RU00 - All variables shall have been written tobefore being read.” \f “Reliability“ \l 9}
Portability{ TC “RU00 - All variables shall have been written tobefore being read.” \f “Portability“ \l 9}
Severity3
{ TC “RU00 - Allvariables shall havebeen written to beforebeing read.” \f “3“ \l 9}
Rationale According to the language or to the compiler, a variable may or not beinitialised. Therefore, if a variable has not been written before being read,the value may be unknown or changed . This can lead to an unintendedbehaviour of the software. See also rules RU30, RU03, OO51
Exception None
Example None
Assessment Programming rule checkingSource code inspection
EVA-102/01/451Page 75
RU30 - A local variable shall always be initialised.
LanguagesC
{{ TC “RU30 - A local variable shall always beinitialised.” \f “C“ \l 9}}
CharacteristicsReliability
{ TC “RU30 - A local variable shall always be initialised.”\f “Reliability“ \l 9}
Portability{ TC “RU30 - A local variable shall always be initialised.”\f “Portability“ \l 9}
Severity2
{ TC “RU30 - A localvariable shall always beinitialised.” \f “2“ \l 9}
Rationale In C, static and global variables are automatically initialised to zero bythe compiler. Local variables, however, may or may not be initialised,and therefore no reliance should be placed on this mechanism. In order toavoid any use of garbage, all variables should have been written to beforethey are read (see rule RU00).Although this is not an ideal solution, as it permits possibly meaninglessinitial values to be used in the code, an explicit initialisation of a variableis a satisfactory strategy to achieve the intent.This does not necessarily require initialisation at declaration. If thevariable is going to be used close to where it is declared, then it can beinitialised in the declaration. If not, it is probably better practice toinitialise it just before its first use. Static and global variables shall be initialised when defined by thedeveloper. A string type variable will be initialised by "" if empty or by anappropriate string between " ".The "0" or "1" literal values shall not be used to initialise non numericvariables. Appropriate symbolic constants shall be specifically definedand used: (TRUE or FALSE for "boolean" variable, NULL for pointer,see rule RU03)All elements of arrays and structures shall receive a value. Braces shallbe used to indicate and match the structure of the resource. This rule is a refinement of the rule RU00.
Exception None
Example/* incorrect : */int array[MAX_LIN][MAX_COL] = {1, 2, 3, 4, 5, 6};
/* correct : */int array[MAX_LIN][MAX_COL] = { {1, 2},
{3, 4},{5, 6}
};
EVA-102/01/451Page 76
char name[MAX_STR] = "";
int n = 0, int max; int nb_sensor;
/* Beginning of the function */nb_sensor = 10;(void) strcpy(name, "JEAN");...for (max=0, i=0; i<n; i++){ ...}
Assessment Programming rule checkingSource code inspection
EVA-102/01/451Page 77
RU03 - A pointer shall always be initialised.
LanguagesC
{{ TC “RU03 - A pointer shall always beinitialised.” \f “C“ \l 9}}
CharacteristicsMaintainability
{ TC “RU03 - A pointer shall always be initialised.” \f“Maintainability“ \l 9}
Reliability{ TC “RU03 - A pointer shall always be initialised.” \f“Reliability“ \l 9}
Severity2
{ TC “RU03 - A pointershall always beinitialised.” \f “2“ \l 9}
Rationale A pointer shall be correctly initialised to limit risks of unexpected effects.If it cannot be initialised to point to a valid object, it shall be initialised toNULL.In the C language, when a pointer is defined, it does not have a memorylocation associated with it. Using an uninitialised pointer may overwritean unexpected portion of memory. Incorrectly overwriting memory cancause serious problems, including system crashes.This rule is a refinement of the rule RU00.
Exception None
Exampleint i;int *pi = &i;
int *pj = NULL;
char *pi;p = malloc(strlen(name) + 1);if (p == NULL){ /* could not allocate memory */ ...;}
Assessment C programming rule checking
EVA-102/01/451Page 78
OO51 – Constructor shall initialise all data members.
LanguagesJava
{{ TC “OO51 – Constructor shall initialise all datamembers.” \f “Java“ \l 9}}
C++{{ TC “OO51 – Constructor shall initialise all datamembers.” \f “+“ \l 9}}
CharacteristicsReliability
{ TC “OO51 – Constructor shall initialise all datamembers.” \f “Reliability“ \l 9}
Severity1
{ TC “OO51 –Constructor shallinitialise all datamembers.” \f “1“ \l 9}
Rationale This ensure that all data members have been written before being read.This rule is a refinement of the rule RU00.
Exception None
Example// incorrectclass A {
private int a = 0;private float b;A () {
this.a = 1;}
}
//correctclass A {
private int a = 0;private float b;A () {
this.b = 0.1;}
}
Assessment Programming rule checking
EVA-102/01/451Page 79
OO52 – Static methods and fields shall not be accessed through an object.
LanguagesJava
{{ TC “OO52 – Static methods and fields shall notbe accessed through an object.” \f “Java“ \l 9}}
C++{{ TC “OO52 – Static methods and fields shall notbe accessed through an object.” \f “+“ \l 9}}
CharacteristicsReliability
{ TC “OO52 – Static methods and fields shall not beaccessed through an object.” \f “Reliability“ \l 9}
Severity2
{ TC “OO52 – Staticmethods and fields shallnot be accessed throughan object.” \f “2“ \l 9}
Rationale Static methods and fields are not tied to any particular object instance ofthe class. A static method can be called even if any object instance hasbeen created.There are two ways to refer to a static field and method: it can beaccessed via an object or it can be referred to by its class name.The second way is preferred since it emphasises the method or field’sstatic nature and avoids confusion between classes and instances.
Exception None
Example // incorrectclass A {
static void staticMethod();void method();
public static void main(String args[]) {A objectA = new A();objectA.staticMethod(); // violationobjectA.method();
}
}
// correctclass A {
static void staticMethod();void method();
public static void main(String args[]) {A objectA = new A();A.staticMethod(); // through clas nameobjectA.method();
}
}
Assessment Programming rule checking
EVA-102/01/451Page 80
RC05 - A for statement counter shall not be modified inside the loop.
LanguagesALL
{{ TC “RC05 - A for statement counter shall notbe modified inside the loop.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “RC05 - A for statement counter shall not bemodified inside the loop.” \f “Maintainability“ \l 9}
Reliability{ TC “RC05 - A for statement counter shall not bemodified inside the loop.” \f “Reliability“ \l 9}
Severity2
{ TC “RC05 - A forstatement counter shallnot be modified insidethe loop.” \f “2“ \l 9}
Rationale In the body of the for loop, the counter shall not be modified and shallbe independent of the processing. If the exit value depends of the processing in the body of the loop, awhile control statement should be used instead of a for one.
Exception None
Example/* incorrect: altering for counter */for ( i = 0; i != the_value; i++ ){ ...; if (condition) { ...; i++; } ...;}
Assessment C programming rule checking
EVA-102/01/451Page 81
RU06 - Floating point variables shall not be used as loop counters.
LanguagesALL
{{ TC “RU06 - Floating point variables shall notbe used as loop counters.” \f “ALL“ \l 9}}
CharacteristicsReliability
{ TC “RU06 - Floating point variables shall not be used asloop counters.” \f “Reliability“ \l 9}
Portability{ TC “RU06 - Floating point variables shall not be used asloop counters.” \f “Portability“ \l 9}
Severity2
{ TC “RU06 - Floatingpoint variables shall notbe used as loopcounters.” \f “2“ \l 9}
Rationale A loop counter is a variable whose value is tested to determinetermination of the loop. Floating point shall not be used for this purpose.Rounding and truncations errors can be propagated through the loopsteps, causing significant inaccuracies in the loop variable, and possiblygiving unexpected results when the termination test is performed.For example, the number of times the loop is performed may vary fromone implementation to another, and be therefore unpredictable.
Exception None
Example/* incorrect */float computed_number;...;for (i = 0; i < computed_number; i++){ ...;}
// correctfloat computed_number;int number;...;number = intValue(computed_number);for (i = 0; i < number; i++){ ...;}
Assessment Programming rule checking
EVA-102/01/451Page 82
RU07 - Type casting from any type to or from pointers shall not be used.
LanguagesC
{{ TC “RU07 - Type casting from any type to orfrom pointers shall not be used.” \f “C“ \l 9}}
CharacteristicsPortability
{ TC “RU07 - Type casting from any type to or frompointers shall not be used.” \f “Portability“ \l 9}
Severity3
{ TC “RU07 - Typecasting from any type toor from pointers shallnot be used.” \f “3“ \l 9}
Rationale Pointers types shall not be converted (cast) to other types (includingpointer types), nor shall other types be cast to pointers. This can lead toundefined or implementation-dependent behaviour, and also circumventstype integrity checking.
Exception Implicit casts of pointer types from and to void* are permitted. Theiruse is mandated by some functions of the standard library.
Example/* incorrect use */int i;i = (int)ai;i = i + 3 * sizeof(int);ai = (int*)i;
/* allowed use */
int *ai = malloc(i_count * sizeof(int));
memcpy (ai, array, array_size);
Assessment Programming rule checking
EVA-102/01/451Page 83
RC03 - Floating point variables shall not be tested for exact equality orinequality.
LanguagesALL
{{ TC “RC03 - Floating point variables shall notbe tested for exact equality or inequality.” \f“ALL“ \l 9}}
CharacteristicsPortability
{ TC “RC03 - Floating point variables shall not be testedfor exact equality or inequality.” \f “Portability“ \l 9}
Reliability{ TC “RC03 - Floating point variables shall not be testedfor exact equality or inequality.” \f “Reliability“ \l 9}
Severity1
{ TC “RC03 - Floatingpoint variables shall notbe tested for exactequality or inequality.”\f “1“ \l 9}
Rationale The inherent nature of floating point types is such that comparisons ofequality will often not evaluate to true even although they are expectedto. In addition the behaviour of such a comparison cannot be predictedbefore execution, and may well vary from one implementation toanother.In this context, equality shall be tested as being within an interval.
Exception None
Example/* correct */#include <math.h>double d1;double d2;double epsilon;...;if (fabs(d1-d2) <= epsilon){ /* equality */ ...;}else{ /* different */ ...;}
Assessment Programming rule checking
EVA-102/01/451Page 84
RU10 - The result of a non void function shall always be used.
LanguagesC
{{ TC “RU10 - The result of a non void functionshall always be used.” \f “C“ \l 9}}
CharacteristicsReliability
{ TC “RU10 - The result of a non void function shallalways be used.” \f “Reliability“ \l 9}
Severity3
{ TC “RU10 - Theresult of a non voidfunction shall always beused.” \f “3“ \l 9}
Rationale A function always returns a result. No usage of it may denote a missingor unintended processing.On the opposite, the values returned by void functions shall not be used.
Exception The result of some functions of the C standard libraries (e.g. strcpy)may be considered as useless.
Exampleint check_state(int x, int y, int z)
/* incorrect */check_state(x, y, z);
/* correct */status = check_state(x, y, z);
Assessment Programming rule checking
EVA-102/01/451Page 85
KS51 - The IFS internal variable shall not be modified.
LanguagesKorn shell
{{ TC “KS51 - The IFS internal variable shall notbe modified.” \f "Korn shell" \l 9}}
CharacteristicsReliability
{{ TC “KS51 - The IFS internal variable shall not bemodified.” \f “Reliability“ \l 9}}
Severity2
{ TC “KS51 - The IFSinternal variable shallnot be modified.” \f “2“\l 9}
Rationale The value of the IFS variable is used for various critical operations, forinstance, separating the words on the command line. Therefore, modifying this variable, even for a short period of time, maymodify the behaviour of all commands called during this period of time.Side effects may happen due to the inheritance of the IFS variable by allthe sub-processes.
Exception None
Example None
Assessment Source code inspection
EVA-102/01/451Page 86
KS52 - An internal script function shall be preferred to an externalcommand.
LanguagesKorn shell
{{ TC “KS52 - An internal script function shall bepreferred to an external command.” \f "Korn shell"\l 9}}
Perl{{ TC “KS52 - An internal script function shall bepreferred to an external command.” \f “l“ \l 9}}
CharacteristicsEfficiency
{{ TC “KS52 - An internal script function shall bepreferred to an external command.” \f “Efficiency“ \l 9}}
Severity2
{ TC “KS52 - Aninternal script functionshall be preferred to anexternal command.” \f“2“ \l 9}
Rationale The call to an internal script (e.g. Korn shell, Perl) function is less timeconsuming than a call to an external command.This rule is particularly important when the call is located within a loop.
Exception None
Example In Korn-Shell# In Korn Shell: to read the current directory# incorrect: external command/usr/bin/pwd
# correct: internal functionpwd
In PERL
# incorrectsystem (“rm –f”);
# correctunlink($foo);
Assessment Source code inspection
EVA-102/01/451Page 87
KS53- All temporary files shall be deleted as soon as possible.
LanguagesKorn shell
{{ TC “KS53- All temporary files shall be deletedas soon as possible.” \f "Korn shell" \l 9}}
CharacteristicsEfficiency
{{ TC “KS53- All temporary files shall be deleted as soonas possible.” \f “Efficiency“ \l 9}}
Severity2
{ TC “KS53- Alltemporary files shall bedeleted as soon aspossible.” \f “2“ \l 9}
Rationale Deleted temporary files as soon as possible allows to keep available moredisk space. In some context, it could be enough.
Exception None
Example Assuming that the f_temp variable contains the name of the temporaryfile, the following command to be inserted at the beginning of the scriptwill delete the file at the end of the script (i.e. on the EXIT signal).
trap 'rm -f "$f_temp"' EXIT
Assessment Source code inspection
EVA-102/01/451Page 88
KS54 - When a test is made on a character string, it shall take into accountthe case of empty string.
LanguagesKorn shell
{{ TC “KS54 - When a test is made on a characterstring, it shall take into account the case of emptystring.” \f "Korn shell" \l 9}}
CharacteristicsReliability
{{ TC “KS54 - When a test is made on a character string, itshall take into account the case of empty string.” \f“Reliability“ \l 9}}
Severity2
{ TC “KS54 - When atest is made on acharacter string, it shalltake into account thecase of empty string.” \f“2“ \l 9}
Rationale For fault tolerance purpose, the case of an empty string shall always beconsidered.
Exception None
Example# incorrect: when $test is empty,# expr complains about a syntax error.basename=`expr $text : '.*\(/.*\)'
# correctbasename=$(expr "x$text" : 'x.*\(/.*\)')
Assessment Source code inspection
EVA-102/01/451Page 89
CO51 - All memory allocated shall be freed after used allocation.
LanguagesC
{{ TC “CO51 - All memory allocated shall befreed after used allocation.” \f "C" \l 9}}
CharacteristicsReliability
{{ TC “CO51 - All memory allocated shall be freed afterused allocation.” \f “Reliability“ \l 9}}
Efficiency{{ TC “CO51 - All memory allocated shall be freed afterused allocation.” \f “Efficiency“ \l 9}}
Severity2
{ TC “CO51 - Allmemory allocated shallbe freed after usedallocation.” \f “2“ \l 9}
Rationale Freeing the memory after used shall be done systematically to avoid anyrisk of memory overflow.After freeing the memory, the related pointer shall be set to NULL.It is recommended that the component in charge of the allocation will bealso in charge of the freeing.
Exception None
Example None
Assessment Memory allocation checking
EVA-102/01/451Page 90
5.6. Operator usage
SC02 - The ternary operator “?:” shall not be used.
LanguagesALL
{{ TC “SC02 - The ternary operator “?:” shall notbe used.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “SC02 - The ternary operator “?:” shall not be used.”\f “Maintainability“ \l 9}
Severity3
{ TC “SC02 - Theternary operator “?:”shall not be used.” \f“3“ \l 9}
Rationale The ?: ternary operator is another form of the if-then-else statement.This operator makes the code more difficult to read and shall be avoidedin favour of the more conventional if-then-else construct.
Exception The ?:”operator may be used in macro statements.
Example/* incorrect */c = (a == b) ? d + f(a) : f(b) - d;
/* correct */if (a == b){ c = d + f(a);}else{ c = f(b) - d;}
/* allowed uses */#define MAX(a, b) ((a) < (b)? (b) : (a))
#define SIZE(s) ( (s) < THRESHOLD ? “little” : “big”)
Assessment Programming rule checking
EVA-102/01/451Page 91
KS61 - The set statement shall not be used to redefine the programarguments.
LanguagesKorn shell
{{ TC “KS61 - The set statement shall not be usedto redefine the program arguments.” \f "Kornshell" \l 9}}
CharacteristicsMaintainability
{{ TC “KS61 - The set statement shall not be used toredefine the program arguments.” \f “Maintainability“ \l9}}
Severity2
{ TC “KS61 - The setstatement shall not beused to redefine theprogram arguments.” \f“2“ \l 9}
Rationale Redefining the arguments of a script using the set statements makesharder to follow the effective values of the arguments within theprogram.
Exception None
Example This program lists recursively all files contained in a list of directoriesgiven as an argument. The search is performed using the set statementto modify the program own arguments
#!/bin/ksh# *** Incorrect ***while [ $# -ne 0 ]do case $1 in -[dD][iI]*) if [ -d $2 ] then directory=$2 shift; shift set - foo "$@" $directory/* fi ;; -*) echo "$1: unknown option ignored" ;; *) if [ -f $1 ] then files="$files $1" elif [ -d $1 ] then directory=$1 shift set - foo "$@" -DIR $directory fi ;; esac shiftdone
echo FOUND FILES:echo $files
EVA-102/01/451Page 92
Assessment Source code inspection
EVA-102/01/451Page 93
KS62 - The [[...]]notation shall be preferred to the test statement.
LanguagesKorn shell
{{ TC “KS62 - The [[...]]notation shall bepreferred to the test statement.” \f "Korn shell" \l9}}
CharacteristicsMaintainability
{{ TC “KS62 - The [[...]]notation shall be preferred to thetest statement.” \f “Maintainability“ \l 9}}
Severity2
{ TC “KS62 - The[[...]]notation shall bepreferred to the teststatement.” \f “2“ \l 9}
Rationale The [[ <condition> ]] notation is easier to analyse than its equivalenttest <condition>.
Exception None
Example#!/bin/ksh# *** Correct ***for filedo if [[ -w $file ]] then ... fidone
#!/bin/ksh# *** Incorrect ***for filedo if test -w $file then ... fidone
Assessment Source code inspection
EVA-102/01/451Page 94
KS63 - The test abbreviations && and || shall not be used.
LanguagesKorn shell
{{ TC “KS63 - The test abbreviations && and ||shall not be used.” \f "Korn shell" \l 9}}
CharacteristicsMaintainability
{{ TC “KS63 - The test abbreviations && and || shall notbe used.” \f “Maintainability“ \l 9}}
Severity2
{ TC “KS63 - The testabbreviations && and ||shall not be used.” \f“2“ \l 9}
Rationale The test abbreviations && and || hide the existence of several executionpaths. Their use may undermine the analysability and testability of theprogram.
Exception To display messages and to define the variable default values.
Example# *** Incorrect *** [ ! -s $file.c ] && cc -c $file.c && echo ok
# *** Correct ***if [[ ! -s $file.c ]]then if cc -c "$file.c" then echo ok fifi
# *** Allowed use ***# Terminating a program in case of error commande || ( echo 'Execution error' 1>&2; exit 1 )
Assessment Source code inspection
EVA-102/01/451Page 95
KS64 - The eval statement shall not be used.
LanguagesKorn shell
{{ TC “KS64 - The eval statement shall not beused.” \f "Korn shell" \l 9}}
CharacteristicsReliability
{{ TC “KS64 - The eval statement shall not be used.” \f“Reliability“ \l 9}}
Severity2
{ TC “KS64 - The evalstatement shall not beused.” \f “2“ \l 9}
Rationale The twice evaluation performed on the eval arguments may create sideeffects.
Exception None
Example None
Assessment Source code inspection
EVA-102/01/451Page 96
KS65 - The internal functions let or $(()) shall be preferred to the exprcommand for arithmetic calculus.
LanguagesKorn shell
{{ TC “KS65 - The internal functions let or $(())shall be preferred to the expr command forarithmetic calculus.” \f "Korn shell" \l 9}}
CharacteristicsEfficiency
{{ TC “KS65 - The internal functions let or $(()) shall bepreferred to the expr command for arithmetic calculus.” \f“Efficiency“ \l 9}}
Severity2
{ TC “KS65 - Theinternal functions let or$(()) shall be preferredto the expr commandfor arithmetic calculus.”\f “2“ \l 9}
Rationale The let or ((...)) internal functions perform various arithmeticcalculus directly on the variables. They avoid using an external commandsuch as expr.The use of the expr command shall be limited to the functionality notcovered by let or ((...)), for instance, the string manipulation.
Exception None
Example The program below iterates 1000 times. #!/bin/ksh# *** Incorrect : ***## The counter is incrementing using expr.#typeset -i count=0while [[ $count -lt 1000 ]]do count=`expr $count+1`done
#!/bin/ksh# *** Correct ***## The counter is incrementing using let.typeset -i count=0while [[ $count -lt 1000 ]]do let count=count+1done
Assessment Source code inspection
EVA-102/01/451Page 97
5.7. Expressions
SC08 – An assignment shall not be embedded within an expression.
LanguagesALL
{{ TC “SC08 – An assignment shall not beembedded within an expression.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “SC08 – An assignment shall not be embedded withinan expression.” \f “Maintainability“ \l 9}
Reliability{ TC “SC08 – An assignment shall not be embedded withinan expression.” \f “Reliability“ \l 9}
Severity2
{ TC “SC08 – Anassignment shall not beembedded within anexpression.” \f “2“ \l 9}
Rationale Assignments nested within expression cause additional side effects. Thebest way to avoid any chance of this leading to a dependence on the orderof evaluation is not to embed assignments within expressions.This also helps to avoid getting "=" and "==" confused. See also ruleRC04
Exception Some usual writing optimisation when calling standard functions in aniterative structure (see examples below).
Example In C
/* incorrect */
x = func(y = z / 3);
if ((x = y) != 0)
if (x = y) /* possible confusion between "=" and "==" */
/* correct */
int c;c = getchar();while (c != EOF){ ... c = getchar();}
y = z / 3;x = func(y);
x = yif (x != 0)
/* Allowed use */
int c;while ((c = getchar()) != EOF){
EVA-102/01/451Page 98
...}
In Perl
// incorrect if ($b = 4) { # statements}// correctif (($line = <FILE>) != 0) { # statements}
Assessment Programming rule checking
EVA-102/01/451Page 99
RC04 – There shall be no assignment at the highest level of a condition.
LanguagesALL
{{ TC “RC04 – There shall be no assignment atthe highest level of a condition.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “RC04 – There shall be no assignment at the highestlevel of a condition.” \f “Maintainability“ \l 9}
Reliability{ TC “RC04 – There shall be no assignment at the highestlevel of a condition.” \f “Reliability“ \l 9}
Severity2
{ TC “RC04 – Thereshall be no assignmentat the highest level of acondition.” \f “2“ \l 9}
Rationale An assignment located at the highest level of a condition may be aconfusion between the "=" and "==" confused. This rule is refinement of rule SC08
Exception None
Example In C
/* incorrect */
if (x = y) /* possible confusion between "=" and "==" */
Assessment Programming rule checking
EVA-102/01/451Page 100
RC02 - The value of an expression shall be the same under any order ofevaluation that the standard allows.
LanguagesC
{{ TC “RC02 - The value of an expression shall bethe same under any order of evaluation that thestandard allows.” \f “C“ \l 9}}
CharacteristicsPortability
{ TC “RC02 - The value of an expression shall be the sameunder any order of evaluation that the standard allows.” \f“Portability“ \l 9}
Severity1
{ TC “RC02 - The valueof an expression shallbe the same under anyorder of evaluation thatthe standard allows.” \f“1“ \l 9}
Rationale Apart from a few operators (notably the function call operator “()”,“&&”, “||”, and “,” (comma)), the order in which sub-expressions areevaluated is unspecified and can vary. This means that no reliance can beplaced on the order of evaluation of sub-expressions, and in particular noreliance can be placed on the order in which side effects occur.When ordering of evaluation is needed, expressions should be broken upinto multiple statements. Note that unlike with some other languages, parentheses in C onlyoverride precedence, and have no other effect on order of evaluation.
Exception None
Example/* This example is erroneous: it may give very different *//* results depending on whether tab[i] is evaluated *//* before i++ or vice versa */
x = tab[i] + i++;
/* correct */x = tab[i] + i;i++;
/* Functions may have additional effects when they are *//* called (e.g. modifying some global data). */
x = f(a) + g(a);
/* could be written as: */x = f(a);x = x + g(a);
Assessment Programming rule checking
EVA-102/01/451Page 101
RC13 - An expression shall not contain function calls using commoneffective parameters or resources.
LanguagesC
{{ TC “RC13 - An expression shall not containfunction calls using common effective parametersor resources.” \f “C“ \l 9}}
CharacteristicsReliability
{ TC “RC13 - An expression shall not contain functioncalls using common effective parameters or resources.” \f“Reliability“ \l 9}
Severity2
{ TC “RC13 - Anexpression shall notcontain function callsusing common effectiveparameters orresources.” \f “2“ \l 9}
Rationale Function may have additional effects when they are called (e.g.modifying some global data). Dependence on order of evaluation couldbe avoided by invoking the function prior to the expression which uses it,making uses of a temporary variable for the value.As an example, consider an expression to get 2 values off a stack,subtract the second from the first and push the result back on the stack:push(pop() - pop()). This will give different results dependingon which of the pop() functions is evaluated first (as an additional sideeffect of pop is to modify the stack).This rule is a refinement of the rule RC02
Exception None
Example/* Incorrect: */x = f(a) + g(a);
/* correct */x = f(a);x = x + g(a);
Assessment Programming rule checkingSource code inspection
EVA-102/01/451Page 102
RC15 - The effective parameters of a call shall not be correlatedexpressions.
LanguagesC
{{ TC “RC15 - The effective parameters of a callshall not be correlated expressions.” \f “C“ \l 9}}
CharacteristicsReliability
{ TC “RC15 - The effective parameters of a call shall notbe correlated expressions.” \f “Reliability“ \l 9}
Severity2
{ TC “RC15 - Theeffective parameters ofa call shall not becorrelated expressions.”\f “2“ \l 9}
Rationale The order in which sub-expressions are evaluated is unspecified and canvary. This means that no reliance can be placed on the order ofevaluation of sub-expressions, and in particular no reliance can be placedon the order in which side effects occur.When ordering of evaluation is needed, expressions should be broken upinto multiple statements.Note: This rule is a refinement of the rule RC02
Exception None
Example/* Incorrect: */printf("%d%d", ++x, power(2,x));
/* correct */x = x + 1;printf("%d%d", x, power(2,x));
Assessment Programming rule checkingSource code inspection
EVA-102/01/451Page 103
SC01 - Multiple assignments shall not be used.
LanguagesALL
{{ TC “SC01 - Multiple assignments shall not beused.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “SC01 - Multiple assignments shall not be used.” \f“Maintainability“ \l 9}
Severity3
{ TC “SC01 - Multipleassignments shall not beused.” \f “3“ \l 9}
Rationale The use of multiple assignments shall be avoided. It is a coding style thatcould only be justified by run-time performance, but if the timebehaviour is not a major issue, it is better to write code easy to analyseinstead of code that may be faster.
Exception None
Example/* incorrect */a = b = c = 0;
/* correct */a = 0;b = 0;c = 0;
Assessment Programming rule checking
EVA-102/01/451Page 104
SC03 - The “*” shall not be used to access to a structure field.
LanguagesC
{{ TC “SC03 - The “*” shall not be used to accessto a structure field.” \f “C“ \l 9}}
CharacteristicsMaintainability
{ TC “SC03 - The “*” shall not be used to access to astructure field.” \f “Maintainability“ \l 9}
Severity2
{ TC “SC03 - The “*”shall not be used toaccess to a structurefield.” \f “2“ \l 9}
Rationale When a field of a structure which is known by its address is accessed, theuse of the -> operator is required as it improves the analysability of thecode.
Exception None
Example/* incorrect */(*struct_ptr).field;
/* correct */struct_ptr->field;
Assessment Programming rule checking
EVA-102/01/451Page 105
SC05 - The level of complexity of a reference shall be limited to 4.
LanguagesC
{{ TC “SC05 - The level of complexity of areference shall be limited to 4.” \f “C“ \l 9}}
CharacteristicsMaintainability
{ TC “SC05 - The level of complexity of a reference shallbe limited to 4.” \f “Maintainability“ \l 9}
Severity2
{ TC “SC05 - The levelof complexity of areference shall belimited to 4.” \f “2“ \l 9}
Rationale Use of more than 4 levels of indirection can seriously impair theanalysability of the code, and shall therefore be avoided.
Exception None
Example/* incorrect */y = *(a[i]->b.c.d[j];
/* correct */x = &(a[i]->b.c);y = *(x->d[j]);
Assessment Programming rule checking
EVA-102/01/451Page 106
SC06 - Explicit casting shall be used in expression with heterogeneoustypes.
LanguagesC
{{ TC “SC06 - Explicit casting shall be used inexpression with heterogeneous types.” \f “C“ \l9}}
C++{{ TC “SC06 - Explicit casting shall be used inexpression with heterogeneous types.” \f “+“ \l 9}}
Java{{ TC “SC06 - Explicit casting shall be used inexpression with heterogeneous types.” \f “Java“ \l9}}
CharacteristicsMaintainability
{ TC “SC06 - Explicit casting shall be used in expressionwith heterogeneous types.” \f “Maintainability“ \l 9}
Reliability{ TC “SC06 - Explicit casting shall be used in expressionwith heterogeneous types.” \f “Reliability“ \l 9}
Severity2
{ TC “SC06 - Explicitcasting shall be used inexpression withheterogeneous types.” \f“2“ \l 9}
Rationale Type conversions occur by default when different types are mixed in anarithmetic expression or across an assignment operator. Use the castoperator to make type conversions explicit rather than implicit.
Exception None
Example
float f;int i;
/* incorrect */f = i;
/* correct */f = (float) i;
Assessment Programming rule checking
EVA-102/01/451Page 107
OO71 – The “equals()” method shall be used to compare two values ofString objects.
LanguagesJava
{{ TC “OO71 – The “equals()” method shall beused to compare two values of String objects.” \f“Java“ \l 9}}
CharacteristicsReliability
{ TC “OO71 – The “equals()” method shall be used tocompare two values of String objects.” \f “Reliability“ \l 9}
Severity1
{ TC “OO71 – The“equals()” method shallbe used to compare twovalues of Stringobjects.” \f “1“ \l 9}
Rationale If two String objects are compared with the operator “==”, it does amemory location comparison and not a "characterwise" comparison.In order to compare the values of the String objects, the boolean equals()method should be used.
Exception None
Example
public class A {int method(String s1, String s2) {
if (s1 == s2) { // incorrect : replace byequals(s1,s2)
return (s1.length() + s2.length());}return 2*s1.length();
}}
Assessment Programming rule checking.
EVA-102/01/451Page 108
SC04 - A condition with more than 4 logical operators shall not containseveral distinct operators.
LanguagesALL
{{ TC “SC04 - A condition with more than 4logical operators shall not contain several distinctoperators.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “SC04 - A condition with more than 4 logicaloperators shall not contain several distinct operators.” \f“Maintainability“ \l 9}
Severity3
{ TC “SC04 - Acondition with morethan 4 logical operatorsshall not contain severaldistinct operators.” \f“3“ \l 9}
Rationale Use of more than 4 logical operators of more than one kind can seriouslyimpair the analysability of the code, and shall therefore be avoided.The logical operators in C are: “&&”, “||” and “!”.
Exception None
Example/* incorrect */if (country == GERMANY && ((region == PRUSSIA && year >= 1610) || (region == SOUTH_GERMANY && year >= 1584) || (region == NORTH_GERMANY && year >= 1700)) && month == FEBRUARY && day == 28 && year % 4 ** 0 && (year % 100 != 0 || year % 400 == 0){tomorrow = 29;}
/* coorect */if (month == FEBRUARY && day == 28){ if (country == GERMANY) { /* SC09: repetitive condition not so complex to analyse */ if ((region == PRUSSIA && year >= 1610) || (region == SOUTH_GERMANY && year >= 1584) || (region == NORTH_GERMANY && year >= 1700)) { if (year % 4 ** 0 && (year % 100 != 0 || year % 400 == 0)) { tomorrow = 29; } } }}
Assessment Programming rule checking
EVA-102/01/451Page 109
RC10 - Bitwise operations shall not be performed on signed integer types.
LanguagesC
{{ TC “RC10 - Bitwise operations shall not beperformed on signed integer types.” \f “C“ \l 9}}
CharacteristicsPortability
{ TC “RC10 - Bitwise operations shall not be performed onsigned integer types.” \f “Portability“ \l 9}
Severity1
{ TC “RC10 - Bitwiseoperations shall not beperformed on signedinteger types.” \f “1“ \l9}
Rationale Bitwise operations ( “~” “<<” “>>” “&” “^” “|” ) are not normallymeaningful on signed integers. Problems can arise if, for example, a rightshift moves the sign bit into the number, or a left shift moves a numericbit into the sign bit.
Exception None
Example/* correct */
unsigned long flag = 1UL<<5;
flag ^= ~0UL;
Assessment Programming rule checking
EVA-102/01/451Page 110
PE71 - Existence of hash element shall be tested with exists.
LanguagesPerl
{{ TC “PE71 - Existence of hash element shall betested with exists.” \f “l“ \l 9}}
CharacteristicsReliability
{{ TC “PE71 - Existence of hash element shall be testedwith exists.” \f “Reliability“ \l 9}}
Efficiency{{ TC “PE71 - Existence of hash element shall be testedwith exists.” \f “Efficiency“ \l 9}}
Severity2
{ TC “PE71 - Existenceof hash element shall betested with exists.” \f“2“ \l 9}
Rationale Perl automatically creates hash elements with a undef value when theyare referenced. Thus, testing the existence of a hash element withdefined $hash{key} modifies the hash.
Exception None
Example # incorrectmy (%hash);if (defined $hash{key}) { ...;}if ($hash{key}) { ...;}
# correctif (exists $hash{key}) { ...;}
Assessment
EVA-102/01/451Page 111
5.8. Code typing
CT00 - A violation of severity 1 rule shall be tagged by a dedicatedcomment.
LanguagesALL
{{ TC “CT00 - A violation of severity 1 rule shallbe tagged by a dedicated comment.” \f “ALL“ \l9}}
CharacteristicsMaintainability
{ TC “CT00 - A violation of severity 1 rule shall be taggedby a dedicated comment.” \f “Maintainability“ \l 9}
Severity1
{ TC “CT00 - Aviolation of severity 1rule shall be tagged by adedicated comment.” \f“1“ \l 9}
Rationale Deviations from this programming guide are acceptable if they enhancecode maintainability, portability or efficiency. Major deviations requirean explanatory comment at each point of departure so that later readerwill know that the deviations are not mistakes, but purposefully are doinga local variation for a good cause.
Exception None
Exampleswitch (sex){case MALE: ...;/* Exception to rule RC01: intentional FALL-THROUGH to avoid duplication of next case code */case FEMALE: ...; break;default:/* Alien ? */ ...; break;}
Assessment Source code inspection
EVA-102/01/451Page 112
CT05 - The code shall be presented in a homogeneous way.
LanguagesALL
{{ TC “CT05 - The code shall be presented in ahomogeneous way.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CT05 - The code shall be presented in ahomogeneous way.” \f “Maintainability“ \l 9}
Severity2
{ TC “CT05 - The codeshall be presented in ahomogeneous way.” \f“2“ \l 9}
Rationale An homogeneous presentation (brace style, indentation, …) improves theanalysability of the code, because the logic of the program is visible “at aglance”.In particular, a nested block of statement shall be indented and theindentation shall be homogeneous within the block.
Exception None
Example/* examples of C, C++ or Java code presentation *//* with the Braces-Stand-Alone style */
/* if structure */if (condition){ ...;}
/* if else structure */if (condition){ ...;}else{ ...;}
/* if else if structure */if (condition_1){ ...;}else if (condition_2){ ...;}else{ ...;}
EVA-102/01/451Page 113
/* switch structure */switch (condition){ case aaaa: ...; break; case bbbb: ...; break; default: ...; break;}
/* while statement */while (condition){ ...;}
/* for statement */for (int; condition; increment){ ...;}
/* do while statement */do{ ...;}while (condition)
Assessment Source code inspection
EVA-102/01/451Page 114
CT17 - Spacing between operands and operators shall be consistent.
LanguagesALL
{{ TC “CT17 - Spacing between operands andoperators shall be consistent.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CT17 - Spacing between operands and operatorsshall be consistent.” \f “Maintainability“ \l 9}
Severity2
{ TC “CT17 - Spacingbetween operands andoperators shall beconsistent.” \f “2“ \l 9}
Rationale An homogeneous spacing between the textual elements improves theanalysability of the code, because the precedence within a statement isvisible “at a glance”.As a proposal to be used by default or adapted according to the language,the following conventions shall be applied:(a) the primary operators "->","." and "[ ]" shall be written with no space
around them,(b) the binary operators should have one space around them, (c) the unary operators should be written with no space between them
and their operands,(d) expressions within parentheses should be written with no space after
the opening parenthesis and no space before the closing parenthesis.
Exception Binary operators may appear with no space around, but they must bindtheir operands tighter than the adjacent operators.
Example In C:
/* primary and unary operators */ tab[i]pt->namest.name!p-bi++(long)m*p&xsizeof(k)
/* binary operators */
c1 = c2;i += j;x + y a < b && < cprint(fmt, a+1, b+1, c+1)
Assessment Source code inspection
EVA-102/01/451Page 115
CT02 - A line shall not exceed the column 80.
LanguagesALL
{{ TC “CT02 - A line shall not exceed the column80.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CT02 - A line shall not exceed the column 80.” \f“Maintainability“ \l 9}
Portability{ TC “CT02 - A line shall not exceed the column 80.” \f“Portability“ \l 9}
Severity3
{ TC “CT02 - A lineshall not exceed thecolumn 80.” \f “3“ \l 9}
Rationale The line length limit is related to the fact that many printers and terminalsare limited to an 80 characters line length. Source code that has longerlines will cause either line wrapping or truncation on these devices. Bothof these behaviours result in code that is hard to read.
Exception None
Example None
Assessment Programming rule checking
EVA-102/01/451Page 116
CT03 - There shall be no more than one statement per line.
LanguagesALL
{{ TC “CT03 - There shall be no more than onestatement per line.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CT03 - There shall be no more than one statementper line.” \f “Maintainability“ \l 9}
Severity3
{ TC “CT03 - Thereshall be no more thanone statement per line.”\f “3“ \l 9}
Rationale Several statements per line are prejudicial to the analysability of thecode.Moving the code around and inserting new code is easier whenmaintaining: this rule improves the changeability of the code.
Exception None
Example/* incorrect */next = prev + (increment % size); prev++;
/* correct */next = prev + (increment % size);prev++;
Assessment Programming rule checking
EVA-102/01/451Page 117
CT04 - There shall be no more than one declaration per line.
LanguagesALL
{{ TC “CT04 - There shall be no more than onedeclaration per line.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CT04 - There shall be no more than one declarationper line.” \f “Maintainability“ \l 9}
Severity3
{ TC “CT04 - Thereshall be no more thanone declaration perline.” \f “3“ \l 9}
Rationale Several declarations per line are prejudicial to the analysability of thecode.Moving the code around and inserting new code is easier whenmaintaining: this rule improves the changeability of the code.Moreover, it encourages commenting.
Exception None
Example/* incorrect */int level, size, lines;
/* correct */int level; /* indentation level */int size; /* size of symbol table */int lines; /* lines read from input */
Assessment Programming rule checking
EVA-102/01/451Page 118
CT06 - Each logical block shall be delimited by braces even if it contains noor one statement.
LanguagesC
{{ TC “CT06 - Each logical block shall bedelimited by braces even if it contains no or onestatement.” \f “C“ \l 9}}
C++{{ TC “CT06 - Each logical block shall bedelimited by braces even if it contains no or onestatement.” \f “+“ \l 9}}
Java{{ TC “CT06 - Each logical block shall bedelimited by braces even if it contains no or onestatement.” \f “Java“ \l 9}}
CharacteristicsMaintainability
{ TC “CT06 - Each logical block shall be delimited bybraces even if it contains no or one statement.” \f“Maintainability“ \l 9}
Severity3
{ TC “CT06 - Eachlogical block shall bedelimited by braceseven if it contains no orone statement.” \f “3“ \l9}
Rationale The systematic use of braces for delimiting statements blocks (fullybracketed syntax) allows to locate quicker the beginning and the end ofthe associated processing. In case of future modification (added statements), there is no risk toforget braces.The use of brace improves the analysability: what is clear to the author ofthe code may not be obvious to others who read the code!
Exception if/else if/else: braces are not mandatory between the else and theif.
Example/* incorrect */if (condition) statement_1;
/* modification quickly written can lead to this mistake */if (condition) statement_1; statement_2;
/* correct */if (condition){ statement_1;}
/* allowed style */if (condition_1){ ...;}else if (condition_2){ ...;}
EVA-102/01/451Page 119
else{ ...;}
Assessment Programming rule checking
EVA-102/01/451Page 120
CT09 - Comments shall not be embedded within statements.
LanguagesC
{{ TC “CT09 - Comments shall not be embeddedwithin statements.” \f “C“ \l 9}}
C++{{ TC “CT09 - Comments shall not be embeddedwithin statements.” \f “+“ \l 9}}
Java{{ TC “CT09 - Comments shall not be embeddedwithin statements.” \f “Java“ \l 9}}
CharacteristicsMaintainability
{ TC “CT09 - Comments shall not be embedded withinstatements.” \f “Maintainability“ \l 9}
Severity3
{ TC “CT09 -Comments shall not beembedded withinstatements.” \f “3“ \l 9}
Rationale Use of embedded comments can seriously impair the analysability of thecode, and shall therefore be avoided.
Exception None
Example/* incorrect */for (i = 1 /* array begins at 1 since this code is translated from fortran */; i <= MAX; i++){ ...;}
/* correct */
/* array begins at 1 since this code is translated fromfortran */for (i = 1; i <= MAX; i++){ ...;}
Assessment Programming rule checking
EVA-102/01/451Page 121
CT26 - Declarations must appear at the beginning of blocks.
LanguagesC
{{ TC “CT26 - Declarations must appear at thebeginning of blocks.” \f “C“ \l 9}}
C++{{ TC “CT26 - Declarations must appear at thebeginning of blocks.” \f “+“ \l 9}}
Java{{ TC “CT26 - Declarations must appear at thebeginning of blocks.” \f “Java“ \l 9}}
CharacteristicsMaintainability
{ TC “CT26 - Declarations must appear at the beginning ofblocks.” \f “Maintainability“ \l 9}
Severity3
{ TC “CT26 -Declarations mustappear at the beginningof blocks.” \f “3“ \l 9}
Rationale Grouping all the necessary declaration at the beginning of the blocksmakes the code easier to read.
Exception None
Example// incorrect// declarations...;for (int i = 1; i <= MAX; i++){ ...;}
// correct// declarationsint i; ;
for (i = 1; i <= MAX; i++){ ...;}
Assessment Programming rule checking
EVA-102/01/451Page 122
CO80 – All headers shall be "Javadoc-like" commented.
LanguagesALL
{{ TC “CO80 – All headers shall be "Javadoc-like" commented.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CO80 – All headers shall be "Javadoc-like"commented.” \f “Maintainability“ \l 9}
Severity3
{ TC “CO80 – Allheaders shall be"Javadoc-like"commented.” \f “3“ \l9}
Rationale The "Javadoc" format allow to automatically produce a detailedhypertext documentation.
Exception None
Example For a Java class or a interface :
/** * <p>Name: <class or interface name> * </p> * <p>Description: <class or interface description> * </p> * @version <version identification> * @date <creation date> * @author <author name> */
For a method :
/** * <p>Name: <method name> * </p> * <p>Description: <method description> * </p> * @param <parameter name> <parameter description> * @return <return value description> * @exception <exception name> * @see <packages used> */
Assessment Source code inspection
EVA-102/01/451Page 123
KS81 - A reference to a variable or a call parameter shall always beenclosed in double quotes (").
LanguagesKorn shell
{{ TC “KS81 - A reference to a variable or a callparameter shall always be enclosed in doublequotes (").” \f "Korn shell" \l 9}}
CharacteristicsReliability
{{ TC “KS81 - A reference to a variable or a call parametershall always be enclosed in double quotes (").” \f“Reliability“ \l 9}}
Severity2
{ TC “KS81 - Areference to a variableor a call parameter shallalways be enclosed indouble quotes (").” \f“2“ \l 9}
Rationale The use of the double quoted notation allows to control the number ofwords on the command line. This fault tolerance programming convention allow to avoid failure whenthe effective value of the variable is an empty string or contains spaces(due or not to expansion).
Exception None
Example In the first case, if the $file variable contains spaces, the grepcommand will receive several arguments.
#!/bin/ksh# *** Incorrect ***grep 'hello' $file
In the second case, the expansion done by the shell will keep the "unity"of the value of $file.
#!/bin/ksh# *** Correct ***grep 'hello' "$file"
Assessment Programming rule checking
EVA-102/01/451Page 124
CT28 - Parameters in a macro definition shall be enclosed by parentheses.
LanguagesC
{{ TC “CT28 - Parameters in a macro definitionshall be enclosed by parentheses.” \f "C" \l 9}}
C++{{ TC “CT28 - Parameters in a macro definitionshall be enclosed by parentheses.” \f “+“ \l 9}}
CharacteristicsReliability
{{ TC “CT28 - Parameters in a macro definition shall beenclosed by parentheses.” \f “Reliability“ \l 9}}
Severity2
{ TC “CT28 -Parameters in a macrodefinition shall beenclosed byparentheses.” \f “2“ \l9}
Rationale Within a definition of a function-like macro, the parameters shall alwaysbe enclosed in parentheses and the whole expression shall always beenclosed in parentheses.If this rule is not adhered to then, when the pre-processor substitutes themacro into the code, the operator precedence may not give the desiredresults.
Exception None
Example/* incorrect */
#define ABS(x) x >= 0 ? x : -x
/* both substitutions will lead to unintended results */
z = ABS(a - b) /* z = a - b >= 0 ? a - b : -a - bz = ABS(a) + 1 /* z = a >= 0 ? a : -a + 1
/* correct */
#define ABS(x) ( ((x) >= 0) ? (x) : (-x)
Assessment Programming rule checking
EVA-102/01/451Page 125
KS82 - Each non elementary regular expression shall be commented.
LanguagesKorn shell
{{ TC “KS82 - Each non elementary regularexpression shall be commented.” \f "Korn shell" \l9}}
Perl{{ TC “KS82 - Each non elementary regularexpression shall be commented.” \f “l“ \l 9}}
CharacteristicsMaintainability
{{ TC “KS82 - Each non elementary regular expressionshall be commented.” \f “Maintainability“ \l 9}}
Severity2
{ TC “KS82 - Each nonelementary regularexpression shall becommented.” \f “2“ \l9}
Rationale The functionality performed by a regular expression is sometimesdifficult to understand. A dedicated comment will certainly be veryhelpful for any future reader (including the developer himself).In Perl, the x modifiers may be used to insert comment and indentation inthe regular expression.
Exception None
Example In Korn shell
# Extracting of the file extensionext=`expr X"$file" : 'X.*\.\(.*\)$'`
# Listing all ".c" file whose name terminates by a series # of digits and a lowercase letter liste=`find . -type f -name '*[0-9][a-z].c' -print`
# Filtering all lines containing successively two series # of digits separated by '+', the' records ' strings, and # either 'in' or 'out'.dd_stats='^[0-9]+\+[0-9]+ records (in|out)$'
In Perl
# Strip C comments (this is simplistic)$cContent =~ s{ /\* # beginning of C comment .*? # match a minimal number of characters \*/ # end of C comment }{}gsx; # s: dot must match newlines too.
Assessment Source code inspection
EVA-102/01/451Page 126
KS83 - Each non standard redirection of command output shall becommented.
LanguagesKorn shell
{{ TC “KS83 - Each non standard redirection ofcommand output shall be commented.” \f "Kornshell" \l 9}}
CharacteristicsMaintainability
{{ TC “KS83 - Each non standard redirection of commandoutput shall be commented.” \f “Maintainability“ \l 9}}
Severity2
{ TC “KS83 - Each nonstandard redirection ofcommand output shallbe commented.” \f “2“\l 9}
Rationale Non standard redirection of command output are sometimes difficult tounderstand. A functional comment will certainly be very helpful for anyfuture reader (including the developer himself).
Exception None
Example With no comment, it is quite difficult to understand what is doing thecode below.
# *** incorrect ***dd_stats='^[0-9]+\+[0-9]+ records (in|out)$''res=`((dd if=/dev/rst0 ibs=63k 2>&1 1>&3 3>&- 4>&-; echo $? >&4) | egrep -v "$dd_stats" 1>&2 3>&- 4>&-) 4>&1`
Assessment Source code inspection
EVA-102/01/451Page 127
5.9. Naming
CO90 - Identifiers shall be meaningful.
LanguagesALL
{{ TC “CO90 - Identifiers shall be meaningful.” \f“ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CO90 - Identifiers shall be meaningful.” \f“Maintainability“ \l 9}
Severity2
{ TC “CO90 -Identifiers shall bemeaningful.” \f “2“ \l 9}
Rationale A precise and suitable meaning to a file, function, type, constant, orvariable gives the programmer as well as the reader of the code moreinformation (nature of the objects used).In C, the ISO standard only requires external identifiers to be significantin the first 6 characters. Thought, this is a severe restriction, most of thecompiler/linkers allow at least 31 character significance (as for theinternal identifiers). Therefore, identifiers shall not rely on significanceof more than 31 characters. However, if the compiler/linker is notcapable of meeting this, then the limit of the compiler shall be used.In the case of a filename, the limit will depend upon the operating systemconstraints on which the software can be adapted.
Exception None
Example Usual naming conventions in C:(a) a void function (e.g. procedure) shall begin by an infinitive verb,(b) "non-Boolean" functions will be substantives representing the
returned value,(c) "boolean" functions shall begin by “TO BE” conjugated,(d) "non-boolean" data shall start by a common name,(e) "boolean" data shall start by “TO BE” conjugated.
MAX_NAME_SIZEComputeAmount()IsEmpty()sequence_number is_full
Assessment Source code inspection
EVA-102/01/451Page 128
CO91 - Identifiers shall conform to homogeneous capitalisation style.
LanguagesALL
{{ TC “CO91 - Identifiers shall conform tohomogeneous capitalisation style.” \f “ALL“ \l 9}}
CharacteristicsMaintainability
{ TC “CO91 - Identifiers shall conform to homogeneouscapitalisation style.” \f “Maintainability“ \l 9}
Severity2
{ TC “CO91 -Identifiers shallconform tohomogeneouscapitalisation style.” \f“2“ \l 9}
Rationale Applying consistently an homogeneous capitalisation style in all the codegives the programmer as well the reader of the code more information(nature of the objects used). See also rules NR01 and NR05.This rule improves the analysability of the code.
Exception None
Example Usual naming conventions in C:
(a) local variable, parameter: lower-case words separated byunderscores.
(b) global variable: prefixed by a string (for instance “g_”), lower-casewords with capitalisation or not, with underscores.
(c) function: capitalisation of the first letter of each word, but do not useunderscores.
(d) constant: upper-case words, separated by underscores.
local_variableg_variable or g_VariableMyFunctionWhichComputeAmount ITEM_NUMBER
Usual naming conventions in Java:
(a) packages: The names of packages are always written in all-lowercaseASCII letters and are singular. The common convention is to usesingular names for package names, such as interface.screen, and not aplural, such as interface.screens. To make package names morereadable identifiers are separated by periods. The Java guidelines forpackaging naming are that you should prefix you package name withyour reverse internet domain name and append your current projectname to the end. In our case: org.ctbto.
(b) interfaces: Interface names should be nouns, in mixed case with thefirst letter of each internal word capitalized. They sould begin with an“i” prefix. Try to keep your interface names simple and descriptive.Use whole words-avoid acronyms and abbreviations (unless theabbreviation is much more widely used than the long form, such asURL or HTML). For example, iUser, iSourceReader.
EVA-102/01/451Page 129
(c) classes: Class names should be nouns, in mixed case with the firstletter of each internal word capitalized. Try to keep your class namessimple and descriptive. Use whole words-avoid acronyms andabbreviations (unless the abbreviation is much more widely used thanthe long form, such as URL or HTML). For example, Customer,Employee.
(d) member functions: Member functions should be strong, activeverbs, in mixed case with the first letter lowercase, with the first letterof each internal word capitalized. For example, run(),deleteVacancy().
(e) getters: Getters are member functions that return the value of a field.You should prefix the word ‘get’ to the name of the field, unless it isa boolean field and then you prefix ‘is’ to the name of the fieldinstead of ‘get’. By following this naming convention you make itobvious that a member function returns a field of an object, and forboolean getters you make it obvious that it returns true or false. Forexample, getResultSetCount(ResultSet rs), isExecutable(). A viablealternative, based on proper English conventions, is to use the prefix‘has’ or ‘can’ instead of ‘is’ for boolean getters. For example, getternames such as hasDependents() and canPrint() make a lot of sensewhen you are reading the code.
(f) setters: Also known as mutators, are member functions that modifythe values of a field. You should prefix the word ‘set’ to the name ofthe field, regardless of the field type. For example,setDisplayMode(String displayMode).
(g) fields: You should use a full English descriptor to name your to makeit obvious what the field represents. Fields that are collections, suchas arrays or vectors, should be given names that are plural to indicatethat they represent multiple values. All names should be in mixedcase with the first letter lowercase, with the first letter of each internalword capitalized. If the name of the field begins with an acronym,such as htmlSource, then the acronym (in this case ‘html’) should becompletely in lowercase. Do not use HTMLSource or hTMLSourcefor the name. For example, firstName, zipCode, unitPrice,discountRate.
(h) local variables: You should use a full English descriptor to make itobvious what the variable represents. Variables that are collections,such as arrays or vectors, should be given names that are plural toindicate that they represent multiple values. All names should be inmixed case with the first letter lowercase, with the first letter of eachinternal word capitalized. If the name of the variable begins with anacronym, such as htmlSource, then the acronym (in this case ‘html’)should be completely in lowercase. Do not use HTMLSource orhTMLSource for the name. For example, query, isDeleted,sqlDatabase.
(i) loop counters: Do not use single letter identifiers like i, l, j or k. Thecode is more understandable with full descriptors likecurrentNumber, recordCounter and so on. Another majordisadvantage of using single letter names for counters, or foranything, is that when you try to search for its use within a code file
EVA-102/01/451Page 130
you will obtain many false hits – consider the ease of searching forloopCounter over the letter i.
(j) collections: A collection, such as an array or a vector, should begiven a pluralized name representing the types of objects stored bythe array. The name should be a full English descriptor with the firstletter of all non-initial words capitalized. For examples,pressReleases, activeVacancies, states. The main advantage of thisconvention is that it helps to distinguish fields that represent multiplevalues (collections) from those that represent single values (non-collections).
(k) constant (final static field): upper-case words, separated byunderscores.
Assessment Source code inspection
EVA-102/01/451Page 131
CO92 - Keywords shall not be used as an identifiers.
LanguagesALL
{{ TC “CO92 - Keywords shall not be used as anidentifiers.” \f "ALL" \l 9}}
CharacteristicsMaintainability
{{ TC “CO92 - Keywords shall not be used as anidentifiers.” \f “Maintainability“ \l 9}}
Severity2
{ TC “CO92 -Keywords shall not beused as an identifiers.”\f “2“ \l 9}
Rationale Using a keyword (case insensitively) as an identifier may be confusing. This rule especially applies in some programming languages (e.g. Kornshell, Fortran) where keywords (for, case, if, etc.) are consideredas keywords only when they appear at a particular place in the code(often as the first word).
Exception None
Example Use of keywords as a variable in Korn shell
# *** Incorrect ***#...do echo $fordone
Assessment Source code inspection
EVA-102/01/451Page 132
NR01 - Constant, macro and enum identifiers shall be in uppercase.
LanguagesC
{{ TC “NR01 - Constant, macro and enumidentifiers shall be in uppercase.” \f “C“ \l 9}}
C++{{ TC “NR01 - Constant, macro and enumidentifiers shall be in uppercase.” \f “+“ \l 9}}
Java{{ TC “NR01 - Constant, macro and enumidentifiers shall be in uppercase.” \f “Java“ \l 9}}
CharacteristicsMaintainability
{ TC “NR01 - Constant, macro and enum identifiers shallbe in uppercase.” \f “Maintainability“ \l 9}
Severity2
{ TC “NR01 - Constant,macro and enumidentifiers shall be inuppercase.” \f “2“ \l 9}
Rationale This naming convention gives the programmer as well the reader of thecode more information (nature of the objects used). In this case, it clearlyappears that these resources which are in uppercase are constant.Note: Macro and enum do not apply to Java.
Exception Exceptions when adhering to other standards (e.g. X Window system)
Example In C:/* correct */const int COUNT = 10;
#define MAX_SIZE 20
typedef enum{ RED, BLUE, GREEN} Colour;
In Java:/* correct */public static final int SIZE = 10;
Assessment Programming rule checking
EVA-102/01/451Page 133
NR02 - An identifier shall not begin by a “_”.
LanguagesC
{{ TC “NR02 - An identifier shall not begin by a“_”.” \f “C“ \l 9}}
CharacteristicsPortability
{ TC “NR02 - An identifier shall not begin by a “_”.” \f“Portability“ \l 9}
Severity1
{ TC “NR02 - Anidentifier shall notbegin by a “_”.” \f “1“\l 9}
Rationale Identifier names with leading underscores are reserved by the ISO Cstandard for system and compiler use and shall not be used for any user-defined identifiers.
Exception None
Example/* incorrect */int _foo_variable;
/* correct */int foo_variable;
Assessment Programming rule checking
EVA-102/01/451Page 134
NR04 - Two “_” character shall not be used consecutively.
LanguagesC
{{ TC “NR04 - Two “_” character shall not beused consecutively.” \f “C“ \l 9}}
CharacteristicsPortability
{ TC “NR04 - Two “_” character shall not be usedconsecutively.” \f “Portability“ \l 9}
Severity1
{ TC “NR04 - Two “_”character shall not beused consecutively.” \f“1“ \l 9}
Rationale Identifiers with double underscore in any position are reserved words inthe C++ language. See also rule NR08.
Exception None
Example/* incorrect */int foo__variable;char foo__array [MAX__LENGTH];
/* correct */int foo_variable;char foo_array [MAX_LENGTH];
Assessment Programming rule checking
EVA-102/01/451Page 135
NR05 - A global variable shall start by a predefined set of characters.
LanguagesC
{{ TC “NR05 - A global variable shall start by apredefined set of characters.” \f “C“ \l 9}}
CharacteristicsMaintainability
{ TC “NR05 - A global variable shall start by a predefinedset of characters.” \f “Maintainability“ \l 9}
Severity2
{ TC “NR05 - A globalvariable shall start by apredefined set ofcharacters.” \f “2“ \l 9}
Rationale A global variable identifier shall be prefixed by a mnemonic (e.g. “g_”)in order to enable the reader to identify them easily.
Exception None
Example/* correct */int g_Count;
Assessment Programming rule checking
EVA-102/01/451Page 136
NR07 - The “$” character shall not be used.
LanguagesC
{{ TC “NR07 - The “$” character shall not beused.” \f “C“ \l 9}}
CharacteristicsPortability
{ TC “NR07 - The “$” character shall not be used.” \f“Portability“ \l 9}
Severity1
{ TC “NR07 - The “$”character shall not beused.” \f “1“ \l 9}
Rationale The “$” character does not belong to the set of characters defined by theISO C standard. All the C compilers do not allow this character.
Exception None
Example/* incorrect */amount_in_$++;
/* correct */amount_in_dollars++;
Assessment Programming rule checking
EVA-102/01/451Page 137
NR08 - Keywords from the C++ language shall not be used.
LanguagesC
{{ TC “NR08 - Keywords from the C++ languageshall not be used.” \f “C“ \l 9}}
CharacteristicsPortability
{ TC “NR08 - Keywords from the C++ language shall notbe used.” \f “Portability“ \l 9}
Severity1
{ TC “NR08 -Keywords from theC++ language shall notbe used.” \f “1“ \l 9}
Rationale C code may need to be processed by a C++ compiler (for example tointerface it with a C++ library).List of C++ keywords [RD8]:
asm enum protected throwauto explicit public typeidbool extern register typenamebreak false reinterpret_cast unioncase float return unsignedcatch for short usingchar friend signed virtualclass goto sizeof voidconst if static volatileconst_cast inline static_cast wchar_tcontinue int struct whiledefault long switchdelete mutable templatedo namespace thisdouble new truedynamic_cast operator tryelse private typedef
Exception None
Example/* incorrect */typedef enum{ false, true} bool;
static bool new;
Assessment Programming rule checking
EVA-102/01/451Page 138
PE90 - sub parameters shall be named explicitly.
LanguagesPerl
{{ TC “PE90 - sub parameters shall be namedexplicitly.” \f “l“ \l 9}}
CharacteristicsMaintainability
{{ TC “PE90 - sub parameters shall be named explicitly.”\f “Maintainability“ \l 9}}
Severity2
{ TC “PE90 - subparameters shall benamed explicitly.” \f“2“ \l 9}
Rationale Perl’s subs do not have named parameters: parameters are gathered in the@_ array. Defining local variables to hold the parameters improves theanalysability.
Exception None
Example # correct
sub foo { my ($par1, $par2, $par3) = @_; ...;}
Assessment Source code inspection
EVA-102/01/451Page 139
KS91 - Each temporary file shall have an unique name for each scriptinstance.
LanguagesKorn shell
{{ TC “KS91 - Each temporary file shall have anunique name for each script instance.” \f "Kornshell" \l 9}}
CharacteristicsReliability
{{ TC “KS91 - Each temporary file shall have an uniquename for each script instance.” \f “Reliability“ \l 9}}
Severity2
{ TC “KS91 - Eachtemporary file shallhave an unique namefor each scriptinstance.” \f “2“ \l 9}
Rationale The use of a unique name for a temporary file may avoid some undefinedbehaviour when the script is executed concurrently by several user orrecursively called.
Exception None
Example# Getting the name of the script without the directoryprogname=`basename $0`# And then, creating a unique temporary file nameresult=/tmp/$progname.$$touch $result
Assessment Source code inspection
EVA-102/01/451Page 140
KS92 - The signals trapped by trap statement shall be defined by theirname rather by their digital code.
LanguagesKorn shell
{{ TC “KS92 - The signals trapped by trapstatement shall be defined by their name rather bytheir digital code.” \f "Korn shell" \l 9}}
CharacteristicsReliability
{{ TC “KS92 - The signals trapped by trap statement shallbe defined by their name rather by their digital code.” \f“Reliability“ \l 9}}
Severity2
{ TC “KS92 - Thesignals trapped by trapstatement shall bedefined by their namerather by their digitalcode.” \f “2“ \l 9}
Rationale It is easier to understand the purpose of the signals when they when theyare referenced by their name.
Exception None
Exampletrap 'rm $copy' EXIT HUP INT QUIT TERM
Assessment Source code inspection
6. APPENDIX A: TABLES OF CONTENT BY LANGUAGE
6.1. Rules applicable to all languages
CO00 - A source file shall not be too long............................................................................................................ 16CT22 - There shall be a file header. ...................................................................................................................... 17CO02 - Duplicating source code shall be avoided. ............................................................................................... 19RU19 - Constants shall be represented by symbols. ............................................................................................. 31C030 - All declared functions shall be used.......................................................................................................... 41CT23 - There shall be a function header. .............................................................................................................. 42CO31 - A function shall follow a standard layout................................................................................................. 43CM00 - A function shall not have an excessive intrinsic complexity. .................................................................. 44CT00 - A function must contain enough comments in order to improve its analysability. ................................... 46RC31 - A function shall validate input parameters before use.............................................................................. 52CF00 - Backward branching shall not be used..................................................................................................... 54CF03 - No statement shall be located after a branching statement or an exit statement within a block................ 59CF04 - The goto statement shall only be used for exception or error processing. ................................................ 60CF05 - A function shall have a single exit point. .................................................................................................. 61CF17 – All if, else if construct shall contain a final else clause............................................................................ 69OO41 - Exceptions shall be used to manage errors.............................................................................................. 70RU04 - All declared variables shall be used. ........................................................................................................ 72RU15 - All formal parameters shall be used. ........................................................................................................ 73RU00 - All variables shall have been written to before being read....................................................................... 74RC05 - A for statement counter shall not be modified inside the loop. ................................................................ 80RU06 - Floating point variables shall not be used as loop counters...................................................................... 81RC03 - Floating point variables shall not be tested for exact equality or inequality............................................. 83SC02 - The ternary operator “?:” shall not be used............................................................................................... 90SC08 – An assignment shall not be embedded within an expression.................................................................... 97RC04 – There shall be no assignment at the highest level of a condition. ............................................................ 99SC01 - Multiple assignments shall not be used................................................................................................... 103SC04 - A condition with more than 4 logical operators shall not contain several distinct operators. ................. 108CT00 - A violation of severity 1 rule shall be tagged by a dedicated comment.................................................. 111CT05 - The code shall be presented in a homogeneous way............................................................................... 112CT17 - Spacing between operands and operators shall be consistent. ................................................................ 114CT02 - A line shall not exceed the column 80. ................................................................................................... 115CT03 - There shall be no more than one statement per line................................................................................ 116CT04 - There shall be no more than one declaration per line. ............................................................................ 117CO80 – All headers shall be "Javadoc-like" commented.................................................................................... 122CO90 - Identifiers shall be meaningful. .............................................................................................................. 127CO91 - Identifiers shall conform to homogeneous capitalisation style............................................................... 128CO92 - Keywords shall not be used as an identifiers.......................................................................................... 131
6.2. Additional rules for the C language
CO01 - A compilation unit shall follow a standard layout.................................................................................... 18NR06 - Absolute pathname shall not be used when including files. ..................................................................... 24CO10 - A header file shall be prevented from multiple inclusions. ...................................................................... 25CT24 - The “#undef” compilation mark shall not be used.................................................................................... 26CT25 - The “#” compilation mark shall be in first column................................................................................... 27RU26 - Global resources shall be declared once in a included file. ...................................................................... 34RU24 - Every local resource shall be declared static. ........................................................................................... 35RU12 - A function shall have a single declaration using prototypes which shall be identical to the functiondefinition. .............................................................................................................................................................. 47RU11 - Every function shall have an explicit return type. .................................................................................... 48RU22 - The number of parameters passed to a function call shall match the function prototype......................... 49RU13 - Functions shall not have a variable number of formal parameters. .......................................................... 50
EVA-102/01/451Page 142
CF01 - The continue statement shall not be used.................................................................................................. 55CF02 - The break statement shall not be used in a loop........................................................................................ 57CF06 - Each case in a switch statement shall be terminated by a break statement. .............................................. 62RC01 - No consecutive non empty case clauses shall be executed in sequence. .................................................. 64CF07 - A default case shall always be specified in a switch statement................................................................. 65CF08 - There shall be only a single break statement in each case of a switch statement...................................... 66CF09 - A switch statement shall contain at least one case. ................................................................................... 68RU30 - A local variable shall always be initialised. ............................................................................................. 75RU03 - A pointer shall always be initialised......................................................................................................... 77RU07 - Type casting from any type to or from pointers shall not be used............................................................ 82RU10 - The result of a non void function shall always be used............................................................................ 84CO51 - All memory allocated shall be freed after used allocation........................................................................ 89RC02 - The value of an expression shall be the same under any order of evaluation that the standard allows. . 100RC13 - An expression shall not contain function calls using common effective parameters or resources. ........ 101RC15 - The effective parameters of a call shall not be correlated expressions. .................................................. 102SC03 - The “*” shall not be used to access to a structure field. .......................................................................... 104SC05 - The level of complexity of a reference shall be limited to 4. .................................................................. 105SC06 - Explicit casting shall be used in expression with heterogeneous types................................................... 106RC10 - Bitwise operations shall not be performed on signed integer types........................................................ 109CT06 - Each logical block shall be delimited by braces even if it contains no or one statement........................ 118CT09 - Comments shall not be embedded within statements. ............................................................................ 120CT26 - Declarations must appear at the beginning of blocks.............................................................................. 121CT28 - Parameters in a macro definition shall be enclosed by parentheses........................................................ 124NR01 - Constant, macro and enum identifiers shall be in uppercase.................................................................. 132NR02 - An identifier shall not begin by a “_”..................................................................................................... 133NR04 - Two “_” character shall not be used consecutively. ............................................................................... 134NR05 - A global variable shall start by a predefined set of characters. .............................................................. 135NR07 - The “$” character shall not be used........................................................................................................ 136NR08 - Keywords from the C++ language shall not be used.............................................................................. 137
6.3. Additional rules for the Java language
CO20 - All declared classes and/or packages shall be used. ................................................................................. 20CO20 - A header file shall not contain more than one class declaration............................................................... 21CM01 - A class shall not have an excessive intrinsic complexity......................................................................... 22OO21 – Fields, methods and classes shall be defined as inaccessible as possible. ............................................... 38OO22 – Instance fields shall be declared “private”............................................................................................... 39OO23 – Public constants shall be defined in a interface. ...................................................................................... 40CF01 - The continue statement shall not be used.................................................................................................. 55CF02 - The break statement shall not be used in a loop........................................................................................ 57CF06 - Each case in a switch statement shall be terminated by a break statement. .............................................. 62RC01 - No consecutive non empty case clauses shall be executed in sequence. .................................................. 64CF07 - A default case shall always be specified in a switch statement................................................................. 65CF08 - There shall be only a single break statement in each case of a switch statement...................................... 66CF09 - A switch statement shall contain at least one case. ................................................................................... 68OO42 - Catch statements shall not have empty bodies. ........................................................................................ 71OO51 – Constructor shall initialise all data members........................................................................................... 78OO52 – Static methods and fields shall not be accessed through an object.......................................................... 79SC06 - Explicit casting shall be used in expression with heterogeneous types................................................... 106OO71 – The “equals()” method shall be used to compare two values of String objects..................................... 107CT06 - Each logical block shall be delimited by braces even if it contains no or one statement........................ 118CT09 - Comments shall not be embedded within statements. ............................................................................ 120CT26 - Declarations must appear at the beginning of blocks.............................................................................. 121NR01 - Constant, macro and enum identifiers shall be in uppercase.................................................................. 132
6.4. Additional rules for the C++ language
CO20 - All declared classes and/or packages shall be used. ................................................................................. 20
EVA-102/01/451Page 143
CO20 - A header file shall not contain more than one class declaration............................................................... 21CM01 - A class shall not have an excessive intrinsic complexity......................................................................... 22NR06 - Absolute pathname shall not be used when including files. ..................................................................... 24CO10 - A header file shall be prevented from multiple inclusions. ...................................................................... 25CT24 - The “#undef” compilation mark shall not be used.................................................................................... 26OO21 – Fields, methods and classes shall be defined as inaccessible as possible. ............................................... 38OO22 – Instance fields shall be declared “private”............................................................................................... 39CF01 - The continue statement shall not be used.................................................................................................. 55CF02 - The break statement shall not be used in a loop........................................................................................ 57CF06 - Each case in a switch statement shall be terminated by a break statement. .............................................. 62RC01 - No consecutive non empty case clauses shall be executed in sequence. .................................................. 64CF07 - A default case shall always be specified in a switch statement................................................................. 65CF08 - There shall be only a single break statement in each case of a switch statement...................................... 66CF09 - A switch statement shall contain at least one case. ................................................................................... 68OO42 - Catch statements shall not have empty bodies. ........................................................................................ 71OO51 – Constructor shall initialise all data members........................................................................................... 78OO52 – Static methods and fields shall not be accessed through an object.......................................................... 79SC06 - Explicit casting shall be used in expression with heterogeneous types................................................... 106CT06 - Each logical block shall be delimited by braces even if it contains no or one statement........................ 118CT09 - Comments shall not be embedded within statements. ............................................................................ 120CT26 - Declarations must appear at the beginning of blocks.............................................................................. 121CT28 - Parameters in a macro definition shall be enclosed by parentheses........................................................ 124NR01 - Constant, macro and enum identifiers shall be in uppercase.................................................................. 132
6.5. Additional rules for the Korn shell language
KS20 - A constant shall be defined with the key word readonly. ......................................................................... 33KS21 - The function local variables shall be defined with typeset. ...................................................................... 37KS31 - A function shall validate the number of received arguments.................................................................... 51KS32 - Only POSIX utilities shall be used. .......................................................................................................... 53KS41 - The "continue n" statement shall not be used. .......................................................................................... 56KS42 - The "break n" statement shall not be used. ............................................................................................... 58KS51 - The IFS internal variable shall not be modified........................................................................................ 85KS52 - An internal script function shall be preferred to an external command. ................................................... 86KS53- All temporary files shall be deleted as soon as possible. ........................................................................... 87KS54 - When a test is made on a character string, it shall take into account the case of empty string. ................ 88KS61 - The set statement shall not be used to redefine the program arguments. .................................................. 91KS62 - The [[...]]notation shall be preferred to the test statement. ....................................................................... 93KS63 - The test abbreviations && and || shall not be used. .................................................................................. 94KS64 - The eval statement shall not be used......................................................................................................... 95KS65 - The internal functions let or $(()) shall be preferred to the expr command for arithmetic calculus. ........ 96KS81 - A reference to a variable or a call parameter shall always be enclosed in double quotes (").................. 123KS82 - Each non elementary regular expression shall be commented................................................................ 125KS83 - Each non standard redirection of command output shall be commented................................................ 126KS91 - Each temporary file shall have an unique name for each script instance................................................ 139KS92 - The signals trapped by trap statement shall be defined by their name rather by their digital code......... 140
6.6. Additional rules for the Perl language
PE01 - use strict shall be used............................................................................................................................... 28PE02 - use warnings shall be used. ....................................................................................................................... 29PE03 - use English shall be used........................................................................................................................... 30PE21 - All sub local variables shall be defined with my....................................................................................... 36KS52 - An internal script function shall be preferred to an external command. ................................................... 86PE71 - Existence of hash element shall be tested with exists. ........................................................................... 110KS82 - Each non elementary regular expression shall be commented................................................................ 125PE90 - sub parameters shall be named explicitly. .............................................................................................. 138
EVA-102/01/451Page 144
7. APPENDIX B: SUMMARY BY QUALITY CHARACTERISTIC
7.1.1. MaintainabilityCO00 - A source file shall not be too long............................................................................................................ 16CT22 - There shall be a file header. ...................................................................................................................... 17CO01 - A compilation unit shall follow a standard layout.................................................................................... 18CO02 - Duplicating source code shall be avoided. ............................................................................................... 19CO20 - All declared classes and/or packages shall be used. ................................................................................. 20CO20 - A header file shall not contain more than one class declaration............................................................... 21CM01 - A class shall not have an excessive intrinsic complexity......................................................................... 22CO10 - A header file shall be prevented from multiple inclusions. ...................................................................... 25CT24 - The “#undef” compilation mark shall not be used.................................................................................... 26PE01 - use strict shall be used............................................................................................................................... 28PE03 - use English shall be used........................................................................................................................... 30RU19 - Constants shall be represented by symbols. ............................................................................................. 31RU26 - Global resources shall be declared once in a included file. ...................................................................... 34RU24 - Every local resource shall be declared static. ........................................................................................... 35OO21 – Fields, methods and classes shall be defined as inaccessible as possible. ............................................... 38OO22 – Instance fields shall be declared “private”............................................................................................... 39OO23 – Public constants shall be defined in a interface. ...................................................................................... 40C030 - All declared functions shall be used.......................................................................................................... 41CT23 - There shall be a function header. .............................................................................................................. 42CO31 - A function shall follow a standard layout................................................................................................. 43CM00 - A function shall not have an excessive intrinsic complexity. .................................................................. 44CT00 - A function must contain enough comments in order to improve its analysability. ................................... 46RU11 - Every function shall have an explicit return type. .................................................................................... 48RU13 - Functions shall not have a variable number of formal parameters. .......................................................... 50CF00 - Backward branching shall not be used..................................................................................................... 54CF01 - The continue statement shall not be used.................................................................................................. 55KS41 - The "continue n" statement shall not be used. .......................................................................................... 56CF02 - The break statement shall not be used in a loop........................................................................................ 57KS42 - The "break n" statement shall not be used. ............................................................................................... 58CF03 - No statement shall be located after a branching statement or an exit statement within a block................ 59CF04 - The goto statement shall only be used for exception or error processing. ................................................ 60CF05 - A function shall have a single exit point. .................................................................................................. 61CF06 - Each case in a switch statement shall be terminated by a break statement. .............................................. 62CF07 - A default case shall always be specified in a switch statement................................................................. 65CF08 - There shall be only a single break statement in each case of a switch statement...................................... 66CF09 - A switch statement shall contain at least one case. ................................................................................... 68OO41 - Exceptions shall be used to manage errors.............................................................................................. 70RU04 - All declared variables shall be used. ........................................................................................................ 72RU15 - All formal parameters shall be used. ........................................................................................................ 73RU03 - A pointer shall always be initialised......................................................................................................... 77RC05 - A for statement counter shall not be modified inside the loop. ................................................................ 80SC02 - The ternary operator “?:” shall not be used............................................................................................... 90KS61 - The set statement shall not be used to redefine the program arguments. .................................................. 91KS62 - The [[...]]notation shall be preferred to the test statement. ....................................................................... 93KS63 - The test abbreviations && and || shall not be used. .................................................................................. 94SC08 – An assignment shall not be embedded within an expression.................................................................... 97RC04 – There shall be no assignment at the highest level of a condition. ............................................................ 99SC01 - Multiple assignments shall not be used................................................................................................... 103SC03 - The “*” shall not be used to access to a structure field. .......................................................................... 104SC05 - The level of complexity of a reference shall be limited to 4. .................................................................. 105SC06 - Explicit casting shall be used in expression with heterogeneous types................................................... 106SC04 - A condition with more than 4 logical operators shall not contain several distinct operators. ................. 108CT00 - A violation of severity 1 rule shall be tagged by a dedicated comment.................................................. 111CT05 - The code shall be presented in a homogeneous way............................................................................... 112CT17 - Spacing between operands and operators shall be consistent. ................................................................ 114
EVA-102/01/451Page 145
CT02 - A line shall not exceed the column 80. ................................................................................................... 115CT03 - There shall be no more than one statement per line................................................................................ 116CT04 - There shall be no more than one declaration per line. ............................................................................ 117CT06 - Each logical block shall be delimited by braces even if it contains no or one statement........................ 118CT09 - Comments shall not be embedded within statements. ............................................................................ 120CT26 - Declarations must appear at the beginning of blocks.............................................................................. 121CO80 – All headers shall be "Javadoc-like" commented.................................................................................... 122KS82 - Each non elementary regular expression shall be commented................................................................ 125KS83 - Each non standard redirection of command output shall be commented................................................ 126CO90 - Identifiers shall be meaningful. .............................................................................................................. 127CO91 - Identifiers shall conform to homogeneous capitalisation style............................................................... 128CO92 - Keywords shall not be used as an identifiers.......................................................................................... 131NR01 - Constant, macro and enum identifiers shall be in uppercase.................................................................. 132NR05 - A global variable shall start by a predefined set of characters. .............................................................. 135PE90 - sub parameters shall be named explicitly. .............................................................................................. 138
7.1.2. ReliabilityPE01 - use strict shall be used............................................................................................................................... 28PE02 - use warnings shall be used. ....................................................................................................................... 29KS20 - A constant shall be defined with the key word readonly. ......................................................................... 33PE21 - All sub local variables shall be defined with my....................................................................................... 36KS21 - The function local variables shall be defined with typeset. ...................................................................... 37RU22 - The number of parameters passed to a function call shall match the function prototype......................... 49KS31 - A function shall validate the number of received arguments.................................................................... 51RC31 - A function shall validate input parameters before use.............................................................................. 52CF06 - Each case in a switch statement shall be terminated by a break statement. .............................................. 62RC01 - No consecutive non empty case clauses shall be executed in sequence. .................................................. 64CF07 - A default case shall always be specified in a switch statement................................................................. 65CF17 – All if, else if construct shall contain a final else clause............................................................................ 69OO41 - Exceptions shall be used to manage errors.............................................................................................. 70OO42 - Catch statements shall not have empty bodies. ........................................................................................ 71RU00 - All variables shall have been written to before being read....................................................................... 74RU30 - A local variable shall always be initialised. ............................................................................................. 75RU03 - A pointer shall always be initialised......................................................................................................... 77OO51 – Constructor shall initialise all data members........................................................................................... 78OO52 – Static methods and fields shall not be accessed through an object.......................................................... 79RC05 - A for statement counter shall not be modified inside the loop. ................................................................ 80RU06 - Floating point variables shall not be used as loop counters...................................................................... 81RC03 - Floating point variables shall not be tested for exact equality or inequality............................................. 83RU10 - The result of a non void function shall always be used............................................................................ 84KS51 - The IFS internal variable shall not be modified........................................................................................ 85KS54 - When a test is made on a character string, it shall take into account the case of empty string. ................ 88CO51 - All memory allocated shall be freed after used allocation........................................................................ 89KS64 - The eval statement shall not be used......................................................................................................... 95SC08 – An assignment shall not be embedded within an expression.................................................................... 97RC04 – There shall be no assignment at the highest level of a condition. ............................................................ 99RC13 - An expression shall not contain function calls using common effective parameters or resources. ........ 101RC15 - The effective parameters of a call shall not be correlated expressions. .................................................. 102SC06 - Explicit casting shall be used in expression with heterogeneous types................................................... 106OO71 – The “equals()” method shall be used to compare two values of String objects..................................... 107PE71 - Existence of hash element shall be tested with exists. ........................................................................... 110KS81 - A reference to a variable or a call parameter shall always be enclosed in double quotes (").................. 123CT28 - Parameters in a macro definition shall be enclosed by parentheses........................................................ 124KS91 - Each temporary file shall have an unique name for each script instance................................................ 139KS92 - The signals trapped by trap statement shall be defined by their name rather by their digital code......... 140
7.1.3. PortabilityNR06 - Absolute pathname shall not be used when including files. ..................................................................... 24
EVA-102/01/451Page 146
CT24 - The “#undef” compilation mark shall not be used.................................................................................... 26CT25 - The “#” compilation mark shall be in first column................................................................................... 27PE01 - use strict shall be used............................................................................................................................... 28RU12 - A function shall have a single declaration using prototypes which shall be identical to the functiondefinition. .............................................................................................................................................................. 47RU22 - The number of parameters passed to a function call shall match the function prototype......................... 49KS32 - Only POSIX utilities shall be used. .......................................................................................................... 53RU00 - All variables shall have been written to before being read....................................................................... 74RU30 - A local variable shall always be initialised. ............................................................................................. 75RU06 - Floating point variables shall not be used as loop counters...................................................................... 81RU07 - Type casting from any type to or from pointers shall not be used............................................................ 82RC03 - Floating point variables shall not be tested for exact equality or inequality............................................. 83RC02 - The value of an expression shall be the same under any order of evaluation that the standard allows. . 100RC10 - Bitwise operations shall not be performed on signed integer types........................................................ 109CT02 - A line shall not exceed the column 80. ................................................................................................... 115NR02 - An identifier shall not begin by a “_”..................................................................................................... 133NR04 - Two “_” character shall not be used consecutively. ............................................................................... 134NR07 - The “$” character shall not be used........................................................................................................ 136NR08 - Keywords from the C++ language shall not be used.............................................................................. 137
7.1.4. EfficiencyKS52 - An internal script function shall be preferred to an external command. ................................................... 86KS53- All temporary files shall be deleted as soon as possible. ........................................................................... 87CO51 - All memory allocated shall be freed after used allocation........................................................................ 89KS65 - The internal functions let or $(()) shall be preferred to the expr command for arithmetic calculus. ........ 96PE71 - Existence of hash element shall be tested with exists. ........................................................................... 110
8. SUMMARY BY SEVERITY
8.1.1. Severity 1: mandatoryCM01 - A class shall not have an excessive intrinsic complexity......................................................................... 22NR06 - Absolute pathname shall not be used when including files. ..................................................................... 24C030 - All declared functions shall be used.......................................................................................................... 41CM00 - A function shall not have an excessive intrinsic complexity. .................................................................. 44CT00 - A function must contain enough comments in order to improve its analysability. ................................... 46RU12 - A function shall have a single declaration using prototypes which shall be identical to the functiondefinition. .............................................................................................................................................................. 47RU11 - Every function shall have an explicit return type. .................................................................................... 48RU22 - The number of parameters passed to a function call shall match the function prototype......................... 49RC31 - A function shall validate input parameters before use.............................................................................. 52CF00 - Backward branching shall not be used..................................................................................................... 54KS41 - The "continue n" statement shall not be used. .......................................................................................... 56CF03 - No statement shall be located after a branching statement or an exit statement within a block................ 59RC01 - No consecutive non empty case clauses shall be executed in sequence. .................................................. 64CF07 - A default case shall always be specified in a switch statement................................................................. 65CF09 - A switch statement shall contain at least one case. ................................................................................... 68OO42 - Catch statements shall not have empty bodies. ........................................................................................ 71RU04 - All declared variables shall be used. ........................................................................................................ 72OO51 – Constructor shall initialise all data members........................................................................................... 78RC03 - Floating point variables shall not be tested for exact equality or inequality............................................. 83RC02 - The value of an expression shall be the same under any order of evaluation that the standard allows. . 100OO71 – The “equals()” method shall be used to compare two values of String objects..................................... 107RC10 - Bitwise operations shall not be performed on signed integer types........................................................ 109CT00 - A violation of severity 1 rule shall be tagged by a dedicated comment.................................................. 111NR02 - An identifier shall not begin by a “_”..................................................................................................... 133NR04 - Two “_” character shall not be used consecutively. ............................................................................... 134
EVA-102/01/451Page 147
NR07 - The “$” character shall not be used........................................................................................................ 136NR08 - Keywords from the C++ language shall not be used.............................................................................. 137
8.1.2. Severity 2: recommendedCO00 - A source file shall not be too long............................................................................................................ 16CT22 - There shall be a file header. ...................................................................................................................... 17CO01 - A compilation unit shall follow a standard layout.................................................................................... 18CO02 - Duplicating source code shall be avoided. ............................................................................................... 19CO20 - All declared classes and/or packages shall be used. ................................................................................. 20CO10 - A header file shall be prevented from multiple inclusions. ...................................................................... 25PE01 - use strict shall be used............................................................................................................................... 28PE02 - use warnings shall be used. ....................................................................................................................... 29PE03 - use English shall be used........................................................................................................................... 30RU19 - Constants shall be represented by symbols. ............................................................................................. 31KS20 - A constant shall be defined with the key word readonly. ......................................................................... 33RU26 - Global resources shall be declared once in a included file. ...................................................................... 34RU24 - Every local resource shall be declared static. ........................................................................................... 35PE21 - All sub local variables shall be defined with my....................................................................................... 36KS21 - The function local variables shall be defined with typeset. ...................................................................... 37OO21 – Fields, methods and classes shall be defined as inaccessible as possible. ............................................... 38OO22 – Instance fields shall be declared “private”............................................................................................... 39OO23 – Public constants shall be defined in a interface. ...................................................................................... 40CO31 - A function shall follow a standard layout................................................................................................. 43RU13 - Functions shall not have a variable number of formal parameters. .......................................................... 50KS31 - A function shall validate the number of received arguments.................................................................... 51KS32 - Only POSIX utilities shall be used. .......................................................................................................... 53CF01 - The continue statement shall not be used.................................................................................................. 55KS42 - The "break n" statement shall not be used. ............................................................................................... 58CF04 - The goto statement shall only be used for exception or error processing. ................................................ 60CF06 - Each case in a switch statement shall be terminated by a break statement. .............................................. 62CF17 – All if, else if construct shall contain a final else clause............................................................................ 69OO41 - Exceptions shall be used to manage errors.............................................................................................. 70RU15 - All formal parameters shall be used. ........................................................................................................ 73RU30 - A local variable shall always be initialised. ............................................................................................. 75RU03 - A pointer shall always be initialised......................................................................................................... 77OO52 – Static methods and fields shall not be accessed through an object.......................................................... 79RC05 - A for statement counter shall not be modified inside the loop. ................................................................ 80RU06 - Floating point variables shall not be used as loop counters...................................................................... 81KS51 - The IFS internal variable shall not be modified........................................................................................ 85KS52 - An internal script function shall be preferred to an external command. ................................................... 86KS53- All temporary files shall be deleted as soon as possible. ........................................................................... 87KS54 - When a test is made on a character string, it shall take into account the case of empty string. ................ 88CO51 - All memory allocated shall be freed after used allocation........................................................................ 89KS61 - The set statement shall not be used to redefine the program arguments. .................................................. 91KS62 - The [[...]]notation shall be preferred to the test statement. ....................................................................... 93KS63 - The test abbreviations && and || shall not be used. .................................................................................. 94KS64 - The eval statement shall not be used......................................................................................................... 95KS65 - The internal functions let or $(()) shall be preferred to the expr command for arithmetic calculus. ........ 96SC08 – An assignment shall not be embedded within an expression.................................................................... 97RC04 – There shall be no assignment at the highest level of a condition. ............................................................ 99RC13 - An expression shall not contain function calls using common effective parameters or resources. ........ 101RC15 - The effective parameters of a call shall not be correlated expressions. .................................................. 102SC03 - The “*” shall not be used to access to a structure field. .......................................................................... 104SC05 - The level of complexity of a reference shall be limited to 4. .................................................................. 105SC06 - Explicit casting shall be used in expression with heterogeneous types................................................... 106PE71 - Existence of hash element shall be tested with exists. ........................................................................... 110CT05 - The code shall be presented in a homogeneous way............................................................................... 112CT17 - Spacing between operands and operators shall be consistent. ................................................................ 114KS81 - A reference to a variable or a call parameter shall always be enclosed in double quotes (").................. 123CT28 - Parameters in a macro definition shall be enclosed by parentheses........................................................ 124
EVA-102/01/451Page 148
KS82 - Each non elementary regular expression shall be commented................................................................ 125KS83 - Each non standard redirection of command output shall be commented................................................ 126CO90 - Identifiers shall be meaningful. .............................................................................................................. 127CO91 - Identifiers shall conform to homogeneous capitalisation style............................................................... 128CO92 - Keywords shall not be used as an identifiers.......................................................................................... 131NR01 - Constant, macro and enum identifiers shall be in uppercase.................................................................. 132NR05 - A global variable shall start by a predefined set of characters. .............................................................. 135PE90 - sub parameters shall be named explicitly. .............................................................................................. 138KS91 - Each temporary file shall have an unique name for each script instance................................................ 139KS92 - The signals trapped by trap statement shall be defined by their name rather by their digital code......... 140
8.1.3. Severity 3: advisableCO20 - A header file shall not contain more than one class declaration............................................................... 21CT24 - The “#undef” compilation mark shall not be used.................................................................................... 26CT25 - The “#” compilation mark shall be in first column................................................................................... 27CT23 - There shall be a function header. .............................................................................................................. 42CF02 - The break statement shall not be used in a loop........................................................................................ 57CF05 - A function shall have a single exit point. .................................................................................................. 61CF08 - There shall be only a single break statement in each case of a switch statement...................................... 66RU00 - All variables shall have been written to before being read....................................................................... 74RU07 - Type casting from any type to or from pointers shall not be used............................................................ 82RU10 - The result of a non void function shall always be used............................................................................ 84SC02 - The ternary operator “?:” shall not be used............................................................................................... 90SC01 - Multiple assignments shall not be used................................................................................................... 103SC04 - A condition with more than 4 logical operators shall not contain several distinct operators. ................. 108CT02 - A line shall not exceed the column 80. ................................................................................................... 115CT03 - There shall be no more than one statement per line................................................................................ 116CT04 - There shall be no more than one declaration per line. ............................................................................ 117CT06 - Each logical block shall be delimited by braces even if it contains no or one statement........................ 118CT09 - Comments shall not be embedded within statements. ............................................................................ 120CT26 - Declarations must appear at the beginning of blocks.............................................................................. 121CO80 – All headers shall be "Javadoc-like" commented.................................................................................... 122