Wednesday, May 8, 2013

Code Comments in Critical, Complex, and/or Obtuse Areas

When writing a portion of code that is critical, complex, or both, taking the time to sprinkle in lots of comments, especially in obtuse, obscure or convoluted logic, can help clarify your assumptions and your understanding of the desired behavior for the code. In the future, this will help both you and others understand the code and its assumptions. You and others will be better able to reason as to whether behavior is correct (just misunderstood) or indeed has a problem. You and others will be better equipped to expand or enhance the functionality.

In such a piece of critical and/or complex logic, if it is difficult to come up with succinct, plain-English comments describing what the code is doing in any of the more complex line(s) of code, this is a good indicator that such lines are ripe for better coding. It might mean moving certain lines to a function to separate out the logic and better "state" what it is doing (via the function's signature and any comments on the function). It might be easier to re-write the lines(s) in a larger amount of code, but a set of code which is significantly easier to read, understand, and/or discuss. 

However, it might be that certain lines of code really are complex and really make sense to be convoluted and complex, in such a way that it takes a few sentences or a paragraph to describe the logic. For these, it is generally better to have that paragraph there describing the code than to not have it. Similar to above, though, if you find the need for such paragraphs in many places in the code, that would suggest it would be better to make the code longer but simpler (more functions, more separation of logic, doing less per-line-of-code, etc.) rather than being the person who wrote the "beast" of code that no one (including you) can fully understand or describe.

No comments:

Post a Comment