What are your “hard rules” about commenting your code?

前端 未结 21 1837
野性不改
野性不改 2020-12-31 16:09

I have seen the other questions but I am still not satisfied with the way this subject is covered.

I would like to extract a distiled list of things

相关标签:
21条回答
  • 2020-12-31 16:23

    When you're writing comments, stop, reflect and ask yourself if you can change the code so that the comments aren't needed. Could you change some variable, class or method names to make things clearer? Would some asserts or other error checks codify your intentions or expectations? Could you split some long sections of code into clearly named methods or functions? Comments are often a reflection of our inability to write (a-hem, code) clearly. It's not always easy to write clearly with computer languages but take some time to try... because code never lies.

    P.S. The fact that you use quotes around "hard rules" is telling. Rules that aren't enforced aren't "hard rules" and the only rules that are enforced are in code.

    0 讨论(0)
  • 2020-12-31 16:25

    Documentation is like sex; when it's good, it's very, very good, and when it's bad, it's better than nothing

    0 讨论(0)
  • 2020-12-31 16:25

    I add 1 comment to a block of code that summarizes what I am doing. This helps people who are looking for specific functionality or section of code.

    I comment any complex algorithm, or process, that can't be figured out at first glance.

    I sign my code.

    0 讨论(0)
  • 2020-12-31 16:26

    A great rule for comments: if you're reading through code trying to figure something out, and a comment somewhere would have given you the answer, put it there when you know the answer.

    Only spend that time investigating once.

    Eventually you will know as you write the places that you need to leave guidance, and the places that are sufficiently obvious to stand alone. Until then, you'll spend time trawling through your code trying to figure out why you did something :)

    0 讨论(0)
  • 2020-12-31 16:26

    We wrote an article on comments (actually, I've done several) here: http://agileinaflash.blogspot.com/2009/04/rules-for-commenting.html

    It's really simple: Comments are written to tell you what the code cannot.

    This results in a simple process: - Write any comment you want at first. - Improve the code so that the comment becomes redundant - Delete the now-redundant comment. - Only commit code that has no redundant comments

    0 讨论(0)
  • 2020-12-31 16:28

    I have one simple rule about commenting: Your code should tell the story of what you are doing; your comments should tell the story of why you are doing it.

    This way, I make sure that whoever inherits my code will be able to understand the intent behind the code.

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