Should I avoid using Java Label Statements?

前端 未结 11 1472
北荒
北荒 2020-11-29 04:27

Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I\'ve never used them before because per

11条回答
  •  囚心锁ツ
    2020-11-29 04:53

    I found labels to be sometimes useful in tests, to separate the usual setup, excercise and verify phases and group related statements. For example, using the BDD terminology:

    @Test
    public void should_Clear_Cached_Element() throws Exception {
        given: {
            elementStream = defaultStream();
            elementStream.readElement();
            Assume.assumeNotNull(elementStream.lastRead());
        }
        when:
            elementStream.clearLast();
        then:
            assertThat(elementStream.lastRead()).isEmpty();
    }
    

    Your formatting choices may vary but the core idea is that labels, in this case, provide a noticeable distinction between the logical sections comprising your test, better than comments can. I think the Spock library just builds on this very feature to declare its test phases.

提交回复
热议问题