Why it is a bad practice to use break/continue labels in OOP (e.g. Java, C#)? [closed]

亡梦爱人 提交于 2019-11-29 10:03:28

The person who told you that would probably means that break and continue are branching statements like goto which are one mechanism of imperative programming.

A break/continue only allow you to jump to an outer statement, which means that you cannot go everywhere in the code. So you stay in the same method object, so it's not incompatible with OOP.

Anyway, saying that break and continue are not OOP is a non-sense. We can discuss about their impact on the readibility maybe but that's all.

Peter Lawrey

break and continue are not functional style programming. There is nothing about OOP which suggestsbreak, continue or even goto within a method is a bad idea.

IMHO using break and continue are discouraged in OOP languages as they can lead to complexity and confusion. As Labels are used rarely they can confuse even further. I would say you should still use them when you feel its the simplest solution to the problem.

// confusing use of LABEL
http://www.google.com/
do {
    if (condition) continue http;
} while(condition2)

another confusing use

GOTO: {
    // code
    if (condition)
         break GOTO; // without a loop
    // code
}

Good use of a label

OUTER: 
for(outer loop) {
   for(inner loop)
      if (condition)
         continue or break OUTER;
}

Odd use of a label

FOUND: {
   for(loop)
      if(found)
          break FOUND;

   // not found
   handle not found
}

Bruce Eckel wrote in "Thinking in Java" following idea: "It’s important to remember that the only reason to use labels in Java is when you have nested loops and you want to break or continue through more than one nested level."

Actually when you don't use lables the workflow of code is more clear in many cases.

The advice not to use break/continue is probably not really related to OOP. It is based on the fact that these statements are similar to the infamous GOTO, which can make code completely unreadable. However, dogmas are bad counsels. The main paradigm should be readability of the code. Jumping out of a loop in the first line using break or continue can be much clearer than putting the whole rest into an if condition.

I think main reason is that code is not so clear with break and continue.

But also may be some performance issues (not related to OOP): CPU use predictors to load instruction in queue before this instruction will be processed. It easy for predictor to detect what instructions to load next for conditional jump and will be harder for unconditional.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!