3 ms·
Adding a comment there is not useful, it should be added only in the function definition if needed. In this case it’s needed because the function does something
by tigershark 6y ago
Adding a comment there is not useful, it should be added only in the function definition if needed.
In this case it’s needed because the function does something unexpected.
I would call it nextPower2(n) rather than npow2 and add a comment in the definition saying that the function returns n if n is a power of 2 because it’s unexpected and it can’t be inferred looking at the function name. As I said before, comments for unexpected behaviours are not only perfectly fine but extremely important.
Also removing all the useless comments will increase the relative importance of the ones remaining since you will have only comments for really important stuff.
Edit: And anyway in the tests you should have at least these two test cases:
Test nextPower2 returns n if it’s a power of 2
Test nextPower2 returns the next power of 2 if n is not a power of 2
- jbay808 6y agoThe comments are informing the reader about the trick that turns npow2 into prevpow2. Your reply seems focused on npow2 itself, not the line npow2(x+1)/2 that I said deserves a comment. I agree that npow2 should have the tests and documentation that you say, but in my example I'm taking that function as given, eg. by a library.