问题描述
我有一个函数可以处理给定的向量,但如果没有给出,也可以自己创建这样的向量.
I have a function that processes a given vector, but may also create such a vector itself if it is not given.
对于这种情况,我看到了两种设计选择,其中函数参数是可选的:
I see two design choices for such a case, where a function parameter is optional:
使其成为一个指针并使其默认为NULL
:
Make it a pointer and make it NULL
by default:
void foo(int i, std::vector<int>* optional = NULL) {
if(optional == NULL){
optional = new std::vector<int>();
// fill vector with data
}
// process vector
}
或者有两个具有重载名称的函数,其中一个省略了参数:
Or have two functions with an overloaded name, one of which leaves out the argument:
void foo(int i) {
std::vector<int> vec;
// fill vec with data
foo(i, vec);
}
void foo(int i, const std::vector<int>& optional) {
// process vector
}
是否有理由更喜欢一种解决方案?
Are there reasons to prefer one solution over the other?
我稍微喜欢第二个,因为我可以使向量成为 const
引用,因为它在提供时只能读取,不能写入.此外,界面看起来更干净(是不是 NULL
只是一个黑客?).并且可能会优化掉间接函数调用导致的性能差异.
I slightly prefer the second one because I can make the vector a const
reference, since it is, when provided, only read, not written. Also, the interface looks cleaner (isn't NULL
just a hack?). And the performance difference resulting from the indirect function call is probably optimized away.
然而,我经常在代码中看到第一个解决方案.除了程序员的懒惰之外,是否有令人信服的理由更喜欢它?
Yet, I often see the first solution in code. Are there compelling reasons to prefer it, apart from programmer laziness?
推荐答案
我绝对喜欢重载方法的第二种方法.
I would definitely favour the 2nd approach of overloaded methods.
第一种方法(可选参数)模糊了方法的定义,因为它不再有一个明确定义的目的.这反过来又增加了代码的复杂性,让不熟悉它的人更难理解它.
The first approach (optional parameters) blurs the definition of the method as it no longer has a single well-defined purpose. This in turn increases the complexity of the code, making it more difficult for someone not familiar with it to understand it.
对于第二种方法(重载方法),每种方法都有明确的目的.每种方法都是结构良好和内聚.一些附加说明:
With the second approach (overloaded methods), each method has a clear purpose. Each method is well-structured and cohesive. Some additional notes:
- 如果有代码需要复制到两个方法中,可以提取到一个单独的方法中,每个重载的方法都可以调用这个外部方法.
- 我会更进一步,为每个方法命名不同以表明方法之间的差异.这将使代码更具自文档性.
- If there's code which needs to be duplicated into both methods, this can be extracted out into a separate method and each overloaded method could call this external method.
- I would go a step further and name each method differently to indicate the differences between the methods. This will make the code more self-documenting.
这篇关于可选函数参数:使用默认参数 (NULL) 还是重载函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!