☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

避免重复的函数实现

8.48 ID_functionRepetition
目录 › next › previous

重复的或过于相似的代码不利于维护。

示例:

struct A {
    int a[10];
    ....
    int* foo() {     // Non-compliant, almost identical to ‘foo() const’
        int* p = a;
        for (int i = 1; i != 10; i++) {
            if (a[i] > *p) {
                p = &a[i];
            }
        }
        return p;
    }
    const int* foo() const {     // Non-compliant, almost identical to ‘foo()’
        const int* p = a;
        for (int i = 1; i != 10; i++) {
            if (a[i] > *p) {
                p = &a[i];
            }
        }
        return p;
    }
};

例中 foo() 返回数组中最大元素的地址,代码与 foo() const 几乎完全相同,当需求有变化时,需要同时修改两个函数,极易造成意料之外的差异,显然是不利于维护的。

本例可通过模板和自动类型推理将公有代码抽取出来:

template <class T>
auto* foo_impl(T* t) {   // The common function extracted
    auto* p = t->a;
    for (auto i = 1; i != 10; i++) {
        if (t->a[i] > *p) {
            p = &t->a[i];
        }
    }
    return p;
}

struct A {
    ....
    int* foo() {
        return foo_impl(this);   // Compliant
    }
    const int* foo() const {
        return foo_impl(this);   // Compliant
    }
};

这样,foo() 与 foo() const 的代码便得到了简化,虽然简化后仍然是相同的,但仅为接口调用,可以接受。

配置

tokenCountThreshold: 符号数量阈值,小于此阈值的函数不参与比较 repetitionRateThreshold: 函数相似度阈值,超过则报出

参考

CWE-1041 C++ Core Guidelines ES.3
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.