参数或方法重载的幻数

Magic numbers for parameters or method overloading?

本文关键字:重载 方法 参数      更新时间:2023-10-16

>我需要为C++中的类实现一个接口,我需要询问与两种集合相关的事件发生,假设这里的人和动作。我需要以所有可能的组合要求人员标识符和操作标识符(所有这些组合,仅指定其中一个标识符或同时指定两个标识符)
选项 1)

// Asks for all events occured for every combination
int getNumberofEvents(float param1)
// Asks for all events occured for idPerson AND all possible value of idAction
int getNumberofEvents(int idPerson, float param1)  
// Asks for all events occured in idAction AND all possible value of idPerson
int getNumberofEvents(int idAction, float param1)
// Asks for all events occured in idPerson AND idAction
int getNumberofEvents(int idPerson, int idAction, float param1)

此选项很容易阅读,但我需要为每个可能的组合实现不同的接口,因此如果我包含新的标识符 (2³),将有 8 种方法。

选项 2)

static const int ALL_PERSONS= 0;
static const int ALL_ACTIONS= 0;
int getNumberofEvents(int idPerson, int idAction, float param1)

对于此选项,只有一个方法接口,但我引入了一个公共幻数来搜索"所有可能的 id"

关于可用性和进一步的可维护性,这将是我现在想到的这两者之间的最佳选择(当然,还有其他更好的选择,我没有包括)。

谢谢。

您可以修改选项 2 以避免幻数,并避免为操作参数传递人员 ID 的问题,反之亦然:

struct Person
{
    explicit Person(int x) : id (x) {}
    int id;
    static Person ALL;
};
Person Person::ALL(0);
struct Action
{
    explicit Action(int x) : id (x) {}
    int id;
    static Action ALL;
};
Action Action::ALL(0);
int getNumberofEvents(const Person& person, const Action& action, float param1);
// ...
int count = getNumberOfEvents(Person(3), Action::ALL, 1.0f);

您似乎正在严重重塑C++包含在标准库中的内容:std::count_if

请注意,它允许任意复杂的条件,因为它接受一个能够过滤和决定哪些对象匹配的函子对象。 有了 C++11,lambda 使供应条件比以往任何时候都更容易。

您可以公开begin()end()迭代器,让用户调用std::count_if,或者编写

int getNumberofEvents(std::function<bool (const descriptor&)> filter, float param1);

并让用户以非常自然的方式编写他们的查询表达式:

getNumberOfEvents([](const descriptor& x) { return x.Action == ACTION_RAISE; }, 5.7);

绝对选择选项 2。 代码的用户不必查找他们想要调用的方法,他们在某些情况下只能使用您定义的常量。 它使用户的生活变得更加容易,只有一个函数名称可以使用,这样他们就不必经常引用您的.h文件来确定他们想要使用的众多函数中的哪一个(命名相同)。