Friday 26 February 2016

Commenting Code

My rules-of-thumb for code commenting:

Don't. If you find yourself writing a comment ask yourself "why am I writing this comment?". Most of the times I've found myself writing a comment is because the code isn't self-commenting: the method/class wasn't small enough; naming - at class, function and/or variable level - was poor and obscured intention; I'd written code which could have been written in a more expressive fashion. I was adding a comment to something which should have been extracted to its own method.

Why not What. As far as possible it should be patently obvious what your code is doing, even at a glance. You may not immediately know how it goes about it, but you often won’t need to: a properly named function in a codebase you trust will tell you what it’s doing; a properly name variable will tell you what is it and what it’s being used for. If the domain logic is a bit peculiar, it might be worth documenting why the thing is being done. But be careful and always take a minute to reflect on whether the domain logic truly is peculiar or whether you are just doing something a bit odd.

No comments:

Post a Comment