3 ms·
If you're working with a language that has closures, I started to have a heuristic: // if you are writing a comment like this // explaining what the next b
by EGreg 10y ago
If you're working with a language that has closures, I started to have a heuristic:
// if you are writing a comment like this
// explaining what the next block of code does
// chances are you should just refactor it
// into a closure
_doWhateverCommentSaid(arg1, arg2, arg3);
it's true that this needlessly adds stack overhead, but this way, you are more likely to structure your code properly, re-use it properly (which more than pays for the stack overhead), and move your closure / method to be more and more global as needed.
Perhaps if you have a comment like this:
f(x); // x matches some assumption
then in fact, you should add validation to f itself, in the form of a function, same as above.
function f(x) {
_theAssumption(x);
}
this habit encourages re-use and proper structuring of code.
in short, comments may be an anti-pattern!
- eridius 10y agoHow does wrapping up code in a closure "fix" the need for comments? And what's wrong with having comments anyway? You haven't demonstrated that comments are an "anti-pattern", all you've demonstrated is that you personally prefer a different style.
- EGreg 10y agoWhenever you put a comment, chances are you should have encapsulated the block there into a reusable block of code.
- eridius 10y agoWhy? You're saying that without any supporting evidence. And frankly, what you're suggesting sounds to me like an unreadable mess. You're going to bloat your code with closures all over the place, simply so you can attach a name to the closure, all to avoid having a simple comment. Naming closures is not a good substitute for comments.
- hoodunit 10y agoNaming closures or functions absolutely is a good substitute for a large class of comments. When you write a comment as a function name, that comment gets maintained when the code changes. It also encourages modularizing your code- often when you write a comment it's a sign that your code is trying to operate conceptually on more than one level and it would be more understandable to separate those levels. I wouldn't say comments are an antipattern but they are a code smell and should be used sparingly and only where the same explanation can't be given through function/variable naming or refactoring.