Aller au contenu

Exercises related to Improving Software Quality

Find out when precondition is missing in a interface

An example of a precondition is when parameters of a function are expected to meet some requirements, e.g. being positive or non zero. Static analysis tool may detect such conditions and are thus helpful in preventing unexpected software behaviors.

From this perspective, what is the precondition for the following function:

int divisor(int x) {
  return 10/x;
}

Exercice 1

Given that this precondition is not tested, code a use of the divisor() function that is detected as an error by cppcheck. After detection of the error by cppcheck, add a precondition check that prevents the unexpected behavior.

Solution

The precondition of the divisor() function is that the parameter x is not 0. Thus a faulty use is to call the function as

int y = divisor(0);
This use should be detected as faulty by cppcheck. A possible fix is
int test(int x) {
  assert(x != 0);
  return 10/x;
}
assert() will usually halt the program depending on the implementation. If a parameter 0 may be accepted with a defined behavior, then this behavior may be implemented differently such as in
int test(int x) {
  if (x == 0) {
    return 0;
  }
  return 10/x;
}
In both cases, cppcheck should now not detect any error for the use of divisor().

Configuring .pre-commit

Exercice 2

For configuring pre-commit, you must first create a “.pre-commit-config.yaml” file. Explain the content of the file:

  1. What does ^main.cpp under files mean? (hint: check https://regex101.com/)
  2. What is the regular expression for running the hooks on “main.cpp” and on the “my_library” subfolder
  3. What does [--std=c++14] mean?
  4. What are the implications of language: system?
Solution
  1. It is a regular expression specifying on what the hooks will be applied. In this case, ^ stands for “start of string”, which means that the hooks will be applied exclusively on the “main.cpp” file. If you are not very familiar with regular expressions, you may use https://regex101.com/) for checking that your project files will be analyzed in the pre-commit phase.
  2. `^(main.cpp)|^(my_library/)
  3. It specifies the C++ standard version to be applied for the analysis.
  4. See explanation on (pre-commit configuration)[https://pre-commit.com/#system]{target="blank”}. As a consequence, one needs to a) ensure the presence of the tool on the machine, b) handle the updates manually and c) manage the accessibility of the tool (e.g. tool present in the $PATH on Windows machines).