4 ms·
This is the advice I give the junior devs I mentor. Write your code clearly and for other developers to read (yes that one-liner is clever, but refactor it so s
by ed312 10y ago
This is the advice I give the junior devs I mentor. Write your code clearly and for other developers to read (yes that one-liner is clever, but refactor it so someone who just worked a 14 emergency deployment can understand it). Comments are for the why - quirky business rules, environment-specific issues, explaining an algorithm. Etc.
- madeofpalk 10y agoAnd a comment explaining why is especially useful when the code is a bit more dense and hard to follow - which is unavoidable at times. IMHO, your default mode should be to not to comment because you should instead focus on 'code as comments' - the code should be easy enough to read that it explains itself. Occasionally (for the reasons you pointed out) you need to fall back to english prose to explain those 'whys'.
- Xylakant 10y agoon top of that the why can extend as to why this specific implementation route was chosen. Some algorithms are less efficient in a general case, but may be much more suitable to the specific case at hand. Things that were tried and proven not to work even though they seem beneficial at first glance.
- wangchow 10y agoI think this is one of those things that is more about wisdom than anything else. You get a sense of what to comment over time and experience. Typically following language best-practices is ideal (pydoc, godoc, Javadoc, etc) so you can get easily-generated documentation for free. Following the standards will make any custom APIs consistent with the standard library API docs. The most important thing though is to ask for peer review on the code. When you are writing code (just like regular language) it will make sense to you regardless of comments or proper variable names. Have someone else read it and tell you what the confusing bits are. If there is no one to do that because you're a lone wolf, then step away from the work for a couple days and play golf or something. Then come back, read the code, and ask if it could be more clear. Then either change variable names or add comments for clarification.
- hliyan 10y agoI can't agree with this enough. My advice is: when the reason for doing something is not self-explanatory, add a brief comment.
- libc 10y agoSome high level "What" comments are useful though even if just for yourself, especially for code that can't be easily broken down into modular units. Even if the code itself is very clean, it's still faster to read that one line comment which summarizes it succinctly in plain English.