Is Break Statement Considered Harmful?

1 minute read

大家知道,”goto”是個不好的寫法, 知名的論文 Go To Considered Harmful 就說明了這件事情,code會變得難以閱讀,並且違反structure programming的 “one entry point and one exit point”

好吧,那我們不用goto這種違反程式正常流程、跳躍式的邏輯,那麼”break”呢?他不是也是直接跳離迴圈違反structure programming嗎?

例如以下的程式是等價的:

while(!isFound) {
  if (number == 0)
    break;
  for (...)
   ...
}
while(!isFound) {
  if (number == 0)
    goto OUT;
  for (...)
   ...
}
OUT:

這樣看來,break與goto根本無異啊!我本來也是嚴格遵守one entry point and one exit point的原則不使用break,但很快發現這樣的原則,反而會讓一個簡單的邏輯複雜化,參考一下Klaim在Stack overflow的一句回答:

When used at the start of a block, as first checks made, they act like preconditions, so it’s good. When used in the middle of the block, with some code around, they act like hidden traps, so it’s bad.

其實break本身並沒有罪,如果你在複雜的迴圈使用它,它當然是破壞程式結構的兇手;但如果是簡單的邏輯判斷,繼續一昧遵循不用break的原則反而使code複雜化,因此適當的使用break是合情合理的!