Is it possible to write good and understandable code without any comments?

前端 未结 20 1408
攒了一身酷
攒了一身酷 2020-12-28 18:35

Can any one suggest what is the best way to write good code that is understandable without a single line of comments?

20条回答
  •  孤独总比滥情好
    2020-12-28 18:56

    Use descriptive variable names and descriptive method names. Use whitespace.

    Make your code read like normal conversation.

    Contrast the use of Matchers in Junit:

    assertThat(x, is(3));
    assertThat(x, is(not(4)));
    assertThat(responseString, either(containsString("color")).or(containsString("colour")));
    assertThat(myList, hasItem("3"));
    

    with the traditional style of assertEquals:

    assertEquals(3, x);
    

    When I look at the assertEquals statement, it is not clear which parameter is "expected" and which is "actual".

    When I look at assertThat(x, is(3)) I can read that in English as "Assert that x is 3" which is very clear to me.

    Another key to writing self-documenting code is to wrap any bit of logic that is not clear in a method call with a clear name.

    if( (x < 3 || x > 17) && (y < 8 || y > 15) )
    

    becomes

    if( xAndYAreValid( x, y ) )  // or similar...
    

提交回复
热议问题