3 ms·
I try to live by a few simple rules regarding code vs comments. Here are ten of them. Some of these are already in other comments, in a different form. 1. Code
by Communitivity 8y ago
I try to live by a few simple rules regarding code vs comments. Here are ten of them. Some of these are already in other comments, in a different form.
1. Code should show not tell. That means the comments I write are typically at the beginning of a class or function rather than scattered throughout on separate lines.
2. Code shows how, comments instruct why. A good comment includes the reasoning behind the algorithms and tradeoff choices chosen by the coder.
3. Good comments include an example of usage
4. Good comments are compatible with an automated documentation framework, such as Javadoc, Doxygen, Rustdoc, and Pydoc
5. Good comments do not include a modification history. Version control and changelogs can handle that.
6. Kill your darlings - Good code follows the KISS principle, and is easily understood, as well as easily maintained
7. Good code is SOLID - This is part of Kill Your Darlings, in a way. To be easily maintained, in many cases, you need to follow SOLID. Here's a good article on SOLID: https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principl...
8. Good code is short - I don't have a firm line count, because it's different based on domain, language, etc. I do try to keep each method/function to no more than a quarter of a screen of code at a reasonable resolution, so that's maybe around 15 lines. With modern optimizing compilers and VMs this will not be a large performance hit, if it's a hit at all, assuming you are following suggested practices. Martinn Fowler follows the same approach, as he explains here: https://martinfowler.com/bliki/FunctionLength.html https://martinfowler.com/bliki/FunctionLength.html
9. Good code has simple, but thought out, names. For the love of Bunnies and Bears everywhere, please do not make a function named similarly to GetFoobarEffectBarIndexFromFoobarSourceBarIndex ( a real function name changed to protect the ~innocent ). Btw, Bunnies and Bears reference is from a Microsoft practice, see https://blogs.msdn.microsoft.com/oldnewthing/20030818-00/?p=42873 https://blogs.msdn.microsoft.com/oldnewthing/20030818-00/?p=....
10. Good code breaks the rules it needs to in order to get the job done, so apply the above rules in context. In other words - make it work, make it fast, then make it elegant. You are the only one who can choose where to stand on any given trade-off line, and that is fine (as long as you know why you are standing there and can explain your reasoning). The surely wrong person is the person who says their way is the only right way in all situations.