我有一个函数simillar:
void fillset(std::set<int>& myset)
{
while(...) {
object[i]->fillset(myset);
}
if(...)
otherfillset(myset)
}
现在我注意到这个函数经常被这样使用:
bool isAllowed() {
std::set<int> myset;
fillset(myset);
return !myset.empty();
}
现在,调用整个fillset()方法对于这种情况是无用的,因为它需要一些时间来执行。 在这种情况下,我可以在找到一个元素后立即返回。 是否有一种简单的方法可以重构这一点而无需复制fillset代码? 我在考虑这样的事情:
template<bool return_as_soon_as_not_empty>
void fillset(std::set<int>& myset)
{
while(...) {
object[i]->fillset(myset);
if( return_as_soon_as_not_empty && !myset.empty()) {
return;
}
}
if(...)
otherfillset(myset)
}
你觉得这个怎么样?欢迎任何其他想法
答案 0 :(得分:3)
您真正想要做的是创建一个新功能canFillSet()
并将其调用。
“修复”fillSet()
方法的所有方法都会导致它从名称和签名做一些不明显的事情=&gt;这些方法是灾难的道路,它们将在以后修改程序时引起错误。
答案 1 :(得分:1)
这样做会改变fillset()
的含义。它不再用所有元素填充集合,它只用第一个填充它。
更好的解决方案是将isAllowed()
级联到对象
bool isAllowed() {
while (...) {
if (object[i]->isAllowed())
return true;
}
return false;
}
答案 2 :(得分:0)
如果您能真正保证填充套装没有副作用,您可以进行建议的更改。但是如果那个集合需要填补其他东西才能正常工作,那么你就有可能改变这种行为。
你可以调用像single_fill
之类的早期返回变量,或者暗示你只是在寻找一个要填充的对象,而不是整个可能的集合。您还应该考虑将该变量设为可选,并默认为false
。