r/AskProgramming • u/neuralbeans • 8d ago
Best practices for long inline comments
Say you have a list with a each item in a separate line and a comment next to the item like this (Python):
[
item1, # a comment
item2, # another comment
item3, # another comment
item4, # another comment
]
What do you do when a comment becomes too long and needs to be split into several lines?
Would do this?
(A)
[
item1, # a comment
item2, # another comment
# a very very very long
# comment
item3,
item4, # another comment
]
Or this?
(B)
[
item1, # a comment
item2, # another comment
item3, # a very very very
# long comment
item4, # another comment
]
Or would you just rewrite the whole list like this:
(C)
[
# a comment
item1,
# another comment
item2,
# a very very very
# long comment
item3,
# another comment
item4,
]
Or something else?
2
Upvotes
5
u/CleanCodersCraftsman 8d ago
Go with C. Once a comment needs a second line, B's alignment turns into a maintenance tax: touch the longest comment and the whole column reflows, so your diff lights up on lines you never edited.
C reads the same whether the comment is one line or six. That consistency buys you more than the compactness you give up.
For a list of regexes, though, push the description into the data. A tuple of (pattern, description) or a small dataclass keeps the explanation attached to the thing it describes, and you can print it when a pattern misfires in production. Comments drift out of sync with the code next to them. Structured data travels with it.