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

前端 未结 21 1839
野性不改
野性不改 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:37

    The comments you write can be revealing about the quality of your code. Countless times I've removed comments in my code to replace them with better, clearer code. For this I follow a couple of anti-commenting rules:

    • If your comment merely explains a line of code, you should either let that line of code speak for itself or split it up into simpler components.
    • If your comment explains a block of code within a function, you should probably be explaining a new function instead.

    Those are really the same rule repeated for two different contexts.

    The other, more normal rules I follow are:

    • When using a dynamically-typed language, document the expectations that important functions make about their arguments, as well as the expectations callers can make about the return values. Important functions are those that will ever have non-local callers.
    • When your logic is dictated by the behavior of another component, it's good to document what your understanding and expectations of that component are.
    0 讨论(0)
  • 2020-12-31 16:37

    There are no hard rules - hard rules lead to dogma and people generally follow dogma when they're not smart enough to think for themselves.

    The guidelines I follow:

    1/ Comments tell what is being done, code tells how it's being done - don't duplicate your effort.

    2/ Comments should refer to blocks of code, not each line. That includes comments that explain whole files, whole functions or just a complicated snippet of code.

    3/ If I think I'd come back in a year and not understand the code/comment combination then my comments aren't good enough yet.

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

    I focus on the why. Because the what is often easy readable. TODO's are also great, they save a lot of time.

    And i document interfaces (for example file formats).

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