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

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

    I think code can be self-documenting to a large degree, and I think it's crucial, but reading even well-written code can be like looking at cells of the human body with a microscope. It sometimes takes comments to really explain the big picture of how pieces of the system fit together, especially if it solves a really complex and difficult problem.

    Think about special data structures. If all that computer scientists had ever published about data structures were well-written code, few would really understand the relative benefit of one data structure over another -- because Big-O runtime of any given operation is sometimes just not obvious from reading the code. That's where the math and amortized analysis presented in articles come in.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题