Tips for writing a clean code
Writing a clean code, it’s not an easy task. First, you’ve to be aware of the language’s good practices and follow them all the time. Secondly, when we spend too much time in the same code, it’s harder to write a clean code because you get too used to it, so something obvious to you can be challenging for another to understand.
1. Learn the good practiced of the language
Each language has uniques characteristics, something that makes sense for one may not make sense for others. Something that can be simple in a language simultaneously can be complicated in another language or have a more straightforward way to do the same thing.
2. Follow the patterns of the project
I’m not saying that if something is wrong or difficult to understand, you should blindly follow. However, sometimes, it’s just preferences, so it is better to follow the project patterns to be consistent within the project.
3. Naming is essential
Write names that give the central idea of what you’re doing, whether the variable or the method. Even abbreviations sometimes can make it difficult to understand. A good example is when you have if statements. It’s much easier to understand if you give the condition a name rather than have the condition there.
Example:
It's easier to understand and gives more context to why you’re doing that
const shouldFetch = name !== null;if (shouldFetch) { … }
comparing to
if (name !== null) { … }
4. Write small functions
If your function is extensive, divide. Each function should only have one responsibility. It makes it easier to understand, maintain and test it.
5. Put comments only if you want to explain a business logic or something that you want to highlight
Your code is your documentation. The cases where you need to add a comment should be rare because your code should be self-sufficient to understand. If you’ve to write a word, it can indicate that your code is not clean or easy to understand.
6. DRY (Don’t repeat yourself)
Don’t have two parts of your code that do the same thing. Just create a function with this part and use how many times you want. This way, it’s easier to maintain.
7. Refactor the code
Always refactor the code to be cleaner and easier to understand if you think so. That action helps in the long term, but be careful not to introduce any bugs.
8. Prefer fewer arguments
Zero or one argument is easiest to maintain and understand.
You can check this article and others on my website: https://www.marinahaack.com/articles/Tips-for-writing-a-clean-code