...
Non Compliant Code Example
The meaning of the value 18 is not clear in this example. Additionally, should this value need to be changed, the programmer would have to change it in multiple places.
Code Block | ||
---|---|---|
| ||
if (age >= 18) { /* Take action */ } ... if (age < 18) { /* Take a different action */ } |
Compliant Solution
The compliant solution replaces 18 with the symbolic constant ADULT_AGE
to clarify the meaning of the code.
When declaring immutable symbolic values such as ADULT_AGE
it is best to use const
or enum
as explained in DCL00-A. Declare immutable values using const or enum.
Code Block | ||
---|---|---|
| ||
enumint {const ADULT_AGE = 18 }; ... if (age >= ADULT_AGE) { /* Take action */ } ... if (age < ADULT_AGE) { /* Take a different action */ } |
In the compliant code it is easy to check if the user is an adult and process accordingly. If the definition of adult changes during iterations of the codebase it is much simpler to replace the value for ADULT_AGE in one place then search for instance of 18 and see if they're appropriate for change.
When declaring immutable symbolic values such as ADULT_AGE it is best to use const or enum as explained in
DCL00-A. Declare immutable values using const or enum
Risk Assessment
Mistakes regarding numeric values can cause unintended consequences if changes are not made uniformly
Risk Assessment
Using numeric literals in code makes that code more difficult to read and understand the programmers intent.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP00 DCL06-A | 1 (low) | 1(unlikely) | 2 (medium) | P2 | L3 |
References
Source: http://www.doc.ic.ac.uk/lab/cplus/c++.rules/chap10.html