可选的函数参数:使用默认参数(NULL)或重载函数? [英] Optional function parameters: Use default arguments (NULL) or overload the function?
问题描述
我有一个函数处理给定的向量,但也可以创建这样的向量本身,如果没有给出。
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?
我稍微喜欢第二个,因为我可以使向量a 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.
第二种方法(重载方法),每个方法都有一个明确的目的。每种方法都是结构良好的和 cohesive 。一些其他注意事项:
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)或重载函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!