DEV Community

Discussion on: "Do not comment on your code, it should be self-documented". Well... I don't agree.

Collapse
 
jackmellis profile image
Jack

I've always found this to be a pretty egotist attitude. "My code is so good you shouldn't need help to understand it".
I've learnt there's a balance in commenting. There are really 3 use cases:

  • you need to explain the "why" of a function or a piece of code. Not the "how" or the "what", which should be clear from the code
  • a function has very complex or business-specific logic and it's 100x easier to talk the reader through what is happening than to just hope they can follow all the branches and call chains
  • you need to explain/excuse something stupid of illogical with how a 3rd party library or api works. If I find myself in this situation I often consider whether I'm using the best library for the job...
Collapse
 
flutterclutter profile image
flutter-clutter

And what is not egoist about thinking that a comment is so good that every reader should get what the corresponding code does? If you know by yourself that your code might be hard to read, then why don't you refactor it instead of adding an explanation? Reminds me of products with manuals that nobody reads. Always asked myself why they don't make the product of intuitive usage instead of writing a manual. Apple was the first big company to understand this.

  • The "why" is an artefact from the business domain and not from the implementation domain. The stake holder should know why he wants things this way. This is nothing that should be explained in the code.
  • Is it, though? If a business-specific logic is complex then it needs to be documented outside of the code. If the code itself is well-written but describes a complicated and ugly business-logic then why would you describe the code?
  • If a library has a complex logic then you need to wrap the library calls in your own class and make the wrapper as understandable as possible. You should also make an interface from it so you can easily switch to a different library when you get the hang of it. The caller of the interface shouldn't care about ugly 3rd party libs.