Java Coding standard / best practices - naming convention for break/continue labels

前端 未结 10 2348
难免孤独
难免孤独 2020-12-15 05:36

Sometimes a labeled break or continue can make code a lot more readable.

OUTERLOOP: for ( ;/*stuff*/; ) {
    //...lots of code

    if ( isEnough() ) break         


        
10条回答
  •  不思量自难忘°
    2020-12-15 06:18

    The convention is to avoid labels altogether.

    There are very, very few valid reasons to use a label for breaking out of a loop. Breaking out is ok, but you can remove the need to break at all by modifying your design a little. In the example you have given, you would extract the 'Lots of code' sections and put them in individual methods with meaningful names.

    for ( ;/*stuff*/; ) 
    {
        lotsOfCode();
    
        if ( !isEnough() )
        {
            moreCode();
        }
    }
    

    Edit: having seen the actual code in question (over here), I think the use of labels is probably the best way to make the code readable. In most cases using labels is the wrong approach, in this instance, I think it is fine.

提交回复
热议问题