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

前端 未结 20 1243
攒了一身酷
攒了一身酷 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:14

    Descriptive names is your obvious first bet.

    Secondly make sure each method does one thing and only one thing. If you have a public method that needs to do many things, split it up into several private methods and call those from the public method, in a way that makes the logic obvious.

    Some time ago I had to create a method that calculated the correlation of two time series.

    To calculate the correlation you also need the mean and standard deviation. So I had two private methods (well actually in this case they were public as they could be used for other purposes (but assuming they couldn't then they would be private)) for calculating A) the mean, B) the standard deviation.

    This sort of splitting up of function into the smallest part that makes sense is probably the most important thing to make a code readable.

    How do you decide where to break up methods. My way is, if the name is obvious e.g. getAddressFromPage it is the right size. If you have several contenders you are probably trying to do too much, if you can't think of a name that makes sense you method may not "do" enough - although the latter is much less likely.

提交回复
热议问题