复杂条件¶
ID: cpp/complex-condition
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- testability
- readability
- maintainability
- statistical
- non-attributable
Query suites:
- cpp-security-and-quality.qls
此规则查找包含超过 5 个连续运算符的布尔表达式,这些运算符不是同一类型(例如交替使用 &&
和 ||
运算符)。相同类型的运算符的长链不会被标记为违反此规则。
复杂的布尔表达式难以阅读。因此,在修改此类表达式时,引入缺陷的风险会增加。将中间结果命名为局部变量将使逻辑更容易阅读和理解。
建议¶
使用局部变量或宏来表示中间值,使条件更容易理解。
示例¶
//This condition is too complex and can be improved by using local variables
bool accept_message =
(message_type == CONNECT && _state != CONNECTED) ||
(message_type == DISCONNECT && _state == CONNECTED) ||
(message_type == DATA && _state == CONNECTED);
//This condition is acceptable, as all the logical operators are of the same type (&&)
bool valid_connect =
message_type == CONNECT &&
_state != CONNECTED &&
time_since_prev_connect > MAX_CONNECT_INTERVAL &&
message_length <= MAX_PACKET_SIZE &&
checksum(message) == get_checksum_field(message);