7 ms·
Ask HN: Tips for Writing Clean Code
I am a mid level programmer but still I face issue with writing clean code.
- Communitivity 5y agoGood code tells a story. You should be able to read the code like English, starting with your inputs, and see how your inputs are transformed/processed into your outputs. Good code is just simple enough. You can, through refactoring make code overly simple (think dozens of 1 line functions, where 3 5-12 line functions do the trick). A function is a scene though - no more, no less. Don't try to stuff a chapter or a novel into one function as that isn't simple at all. Good code is commented with comments that explain and add meaning to the code, rather than repeating what is obvious from the code itself.
- thescribbblr 5y agoWow. Is there any way to avoid commenting on each line or at every function?
- philipswood 5y agoWell-chosen function names (where a function name says what it does), clear variable names (where the name makes it clear what it contains) and using well-named flags to factor complex conditions can make code read as clearly as prose.
- O_H_E 5y agoI understand what you (and @Communitivity) are saying. I know that feeling when code reads a bit like prose, but I'd seriously appreciate examples of public code that reads as clearly as prose
- Communitivity 5y agoSome source of good code: * https://github.com/keras-team/keras/ https://github.com/keras-team/keras/ * https://www.quora.com/Where-can-one-find-examples-of-good-quality-open-source-coding/answer/Toby-Thain https://www.quora.com/Where-can-one-find-examples-of-good-qu...
- aristofun 5y agoTip #1 — don't try to write clean code. Try to solve the task with best quality possible. The quality of outcome (how reliable, performant and stable to edge cases your feature is). Clean code will eventually and naturally come. Don't waste your energy starting from wrong side.
- thescribbblr 5y agoI try to achieve the same but my manager always forces me to write code cleaner so that it doesn't affect the other person who is reviewing it. I am kinda feel like hell when he say so.
- codingdave 5y ago> I am kinda feel like hell when he say so. That may be the bigger problem - listening to feedback is a great way to improve. If receiving that feedback makes you feel bad about your work, fix that response. Embrace the feedback as mentoring towards being a better developer, and be thankful for it. Easier said than done, but if you can adopt a positive attitude towards receiving feedback, odds are you'll be more comfortable taking the advice from your manager and get to a place where you both are happy with your work.
- aristofun 5y agoThen just take each his feedback as a lesson (as long as the feedback is specific) and grow from it. Nothing to feel bad about. It plays excellent together with my tip.