DEV Community

loading...

Discussion on: //TODO: Write a better comment

Collapse
tiguchi profile image
Thomas Iguchi

The linked Medium article still raises a good point, that comments can be seen as an indicator for a special type of code smell. The one that puts a ton of cognitive load on you while trying to make sense of what's going on.

However, in that case the problem is not so much with comments but with the code itself.

I was recently working on an extremely convoluted spaghetti code base that didn't even bother with explaining the obscure if / else if / else if / else sections that spanned over hundreds of lines in a single method. I would have really appreciated comments that explained what was happening there.

I refactored that code and broke out each section that appeared to be doing one unit of work into separate methods (and some of them further down into more methods) with self-describing names. Along the way I found and fixed several serious bugs which were really hard to spot due to the convoluted nature of the original code.

The refactored result doesn't need any comments anymore. Everything is now split into single-purpose methods, and the original main method is now collapsed from several hundred lines to just about 7 method calls, each explaining what's happening. The main reason for that refactor was that I had to write unit-tests for that component. Breaking down complex logic to small single purpose units of work doesn't only make the code more readable but also gives you the extra benefit of easier, more controlled "unit-testability". I wrote for each refactored method a bunch of individual unit test. This would have been very difficult to do while everything was still crammed into the same method.

The Medium article also mentions that kind of refactor and presents it as an example why we should remove comments from code. However, in my case there were no comments in that inherited code base. I was simply dealing with crappy and undocumented code. I would have been extremely grateful for some comments explaining to me what each section did.

There are usually just a handful rare occasions when I decide to add comments to my code. It's when some kind of external system or dependency imposes some odd workarounds that are not obvious to understand, similar to your HashMap example.

However, I do add (JavaDoc) comments as documentation to each type and method. I also try to make sure to provide them with examples, explain under which circumstances exceptions are thrown or under which circumstances null is returned, and so on.

I like to generate documentation from these comments, and I find it quite sad and depressing when I only see type and method names but not a single word written in plain English. But that's my OCD speaking. Over the years I learned to tame my OCD a bit, so I also skip documenting simple getters and setters, where there is no point in explaining what's going on 😄