I know that this is not the answer you are looking for, but do not comment at all. If your code is not clear enough to stand without comment, then you should reorganize it until it is. Jeffrey Palerm o just wrote a blog post that said it best.
Typically, comments tend to document either:
- Code that is too compact. Things that look like this:
++i?--g:hi; - Long blocks of code to be summarized.
- Code that is either one-time or has no clear reason for existing
The following is a simplified example of simply commenting on your exception block and a version that eliminates the need for comments.
bool retries = 0; while (retries < MAX_RETRIES) { try { ... database access code break; } // If under max retries, log and increment, otherwise rethrow catch (SqlException e) { logger.LogWarning(e); if (++retries >= MAX_RETRIES) { throw new MaxRetriesException(MAX_RETRIES, e); } } // Can't retry. Log error and rethrow. catch (ApplicationException e) { logger.LogError(e); throw; } }
While the above comments encourage reuse, you essentially need to support both code and comments. It is possible (and preferable) to reorganize it so that it is clearer without comment.
bool retries = 0; while (canRetry(retries)) { try { ... database access code break; } catch (SqlException e) { logger.LogWarning(e); retries = incrementRetriesOrThrowIfMaxReached(retries, e); } catch (ApplicationException e) { logger.LogError(e); throw; } } ... private void incrementRetriesOrThrowIfMaxReached(int retries, Exception e) { if (++retries >= MAX_RETRIES) throw new MaxRetriesException(MAX_RETRIES, e); return retries; } private bool canRetry(int retries) { return retries < MAX_RETRIES; }
The latter example may seem like a lot of code for very subtle benefits, but the benefits cannot be overestimated. The code is also understandable, but you get the advantage that you do not need to have a separate set of metadata (comments) to explain the code. The code explains itself. If your catch code block is too long and needs comments to be generalized, consider refactoring it for a separate method to improve readability.
source share