这更像是一个入门级问题,但我想知道是否有一个空if语句是一个好习惯.
考虑以下代码:
void RabbitList::purge()
{
if(head == NULL)
{
//cout << "Can't purge an empty colony!" << endl;
}
else
{
//Kill half the colony
for(int amountToKill = (getColonySize()) / 2; amountToKill != 0;)
{
RabbitNode * curr = head;
RabbitNode * trail = NULL;
bool fiftyFiftyChance = randomGeneration(2);
//If the random check succeeded but we're still on the head node
if(fiftyFiftyChance == 1 && curr == head)
{
head = curr->next;
delete curr;
--size;
--amountToKill;
}
//If the random check succeeded and we're beyond the head, but not on last node
else if(fiftyFiftyChance == 1 && curr->next != NULL)
{
trail->next = curr->next;
delete curr;
--size;
--amountToKill;
}
//If the random check succeeded, but we're on the last node
else if(fiftyFiftyChance == 1)
{
trail->next = NULL;
delete curr;
--size;
--amountToKill;
}
//If the random check failed
else
{
trail = curr;
curr = curr->next;
}
}
cout << "Food shortage! Colony has been purged by half." << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,第5行的if语句当前已被注释掉; 这更多是调试文本,我不想再向控制台发送任何反馈.我很确定if语句什么都不做会被认为是不好的做法.我知道我可以回来;
但由于我的返回类型无效,它给了我一个错误.如果我的返回类型不是空的怎么办?
即使你的返回类型是无效的,它在return那里是合法的,当然,因为if有括号,至少这不是一个等待发生的错误.然而,它并不漂亮,需要更多的工作来阅读/理解.
你可以改写它
if(head == NULL) // or if(!head)
return;
....
Run Code Online (Sandbox Code Playgroud)
这应该删除对else的需要,其余的代码现在在函数内部,而不是嵌套的范围,一个快乐的特权.
对于单个分支,直接写就可以了:
if (head != 0) {
// whatever
}
Run Code Online (Sandbox Code Playgroud)
对于多个分支,有时第一个分支为空可以简化以下条件:
if (head == 0) {
// nothing to do
} else if (head->next == 0) {
// whatever
} else {
// whatever else
}
Run Code Online (Sandbox Code Playgroud)
是的,您可以使用附加层编写最后一个:
if (head != 0) {
if (head->next == 0) {
// whatever
} else {
// whatever else
}
}
Run Code Online (Sandbox Code Playgroud)
但第一种形式更清晰,尤其是当第二种形式以三四级 if 结尾时。
哦,还有
if (head == 0)
return;
Run Code Online (Sandbox Code Playgroud)
有时可能很困难,因为它为函数引入了一个额外的退出点。过去我是这种形式的粉丝,但在过去的几年里,我发现我最终一直在移除它。
| 归档时间: |
|
| 查看次数: |
13362 次 |
| 最近记录: |