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

前端 未结 20 1233
攒了一身酷
攒了一身酷 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 19:01

    If you want to code entirely without comments and still have your code be followable, then you'll have to write a larger number of shorter methods. Methods will have to have descriptive names. Variables will also have to have descriptive names. One common method of doing this is to give variables the name of nouns and to give methods the names of verbal phrases. For example:

    account.updateBalance();
    child.givePacifier();
    int count = question.getAnswerCount();
    

    Use enums liberally. With an enum, you can replace most booleans and integral constants. For example:

    public void dumpStackPretty(boolean allThreads) {
        ....
    }
    
    public void someMethod() {
        dumpStackPretty(true);
    }
    

    vs

    public enum WhichThreads { All, NonDaemon, None; }
    public void dumpStackPretty(WhichThreads whichThreads) {
        ....
    }
    
    public void someMethod() {
        dumpStackPretty(WhichThreads.All);
    }
    

提交回复
热议问题