Breaking/continuing out of multiple loops

@Gouvernathor

Discuss doesn’t recognise py as a language for code blocks, you have to use python. I think python3 might also work.

This discussion is causing unpleasant flashbacks to the “structured programming wars” of the 1970s. (I didn’t witness them myself, but as late as 1999 when everyone was frantically re-writing their Cobol programs, a friend of mine was being ordered by his boss not to use functions because GOTO is “more efficient”.)

If you were hoping to convince us that labelled break/continue is better than using functions, I think that you are having the opposite effect.

To me, your example seems so artificial, and implausible, as to be useless as a use-case for multilevel break. If you don’t have a more realistic and convincing use-case, that weakens the argument for multilevel break.

In your example, the first time you find a moon with an atmosphere, you exit the entire planetary system. Surely it would be more realistic to move on to the next moon? And if you find a moon with no titanium, you exit the entire solar system. If you are looking for titanium, why not just move on to the next moon? Why travel to the next system?

def get_titanium(systems):
    """Mine titanium from a moon in one of the given systems."""
    for system in systems:
        for planet in system:
            moon = find_suitable_moon(planet)
            if moon is not None:
                 return mine_titanium(moon)

And lo, we have:

  • no problem with multilevel break;
  • a testable function with a self-documenting name;
  • we can factor the search algorithm into a separate function;
  • which allows us to test it, document it, and use a meaningful name;
  • and having done that, it awakes us to an even more powerful refactoring:
def get_titanium(systems):
    """Mine titanium from somewhere in one of the given systems."""
    for system in systems:
        body = find_suitable_body(system)
        # May return an uninhabitable planet, planetoid, moon, asteroid or comet.
        if body is not None:
            return mine_titanium(body)

I think that justifying this proposal is going to be hard. Break and continue are gotos, and as Uncle Bob explains in the link above, it is mathematically provable that we don’t need gotos.

To make this proposal convincing, we need a realistic example of an algorithm that uses it, and that example needs to be significantly more readable and maintainable than the refactorings into functions, or the use of try…except (also a localised goto).

If you intend to continue to push this idea, I strongly suggest you look at prior art: find languages which have added this capability, and see why they added it.

1 Like