参数或方法重载的幻数
Magic numbers for parameters or method overloading?
>我需要为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文件来确定他们想要使用的众多函数中的哪一个(命名相同)。
相关文章:
- 重载方法的方式会在使用临时调用时生成编译器错误
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- 一种优雅或至少可行的方法,用于使用和接受具有重载方法和运算符的不同大小的文字数组常量
- 使用 nullptr 调用重载方法是不明确的
- 具有重载方法的可变参数数据结构
- C++11 重载方法,并转发到唯一方法
- 获取特定的模板重载方法指针
- std::result_of 应用于 const 重载方法
- 重载方法的类接受模板和基类 - 如何默认某个方法
- 推导模板类重载方法的地址会导致"error: expected primary-expression before ‘decltype’"
- C++如何使用按值传递和按引用传递的重载方法
- 具有原始方法参数派生类的 C++ 重载方法参数
- SWIG:在派生类中处理基类重载方法
- 在c++中的赋值运算符重载方法中删除旧的动态分配内存
- C++选择'wrong'默认参数的重载方法
- 重写重载方法会隐藏一些重载
- 在C++中,如何从父类变量的子类调用重载方法
- 所有重载方法的别名
- 使用 SWIG 在重载C++方法中设置类型