I have been having difficulties in writing clean code. But the series of posts in Medium helped a lot. So here are the links to the posts and my takeaways that are worth sharing from part 1, part 2, part 3, & part 4 of the Writing Clean Code series by Logeshvar L.
- Avoid redundant information. E.g: UserWithNameAndAge is more redundant and is very lengthy. Prefer User
- Be consistent in naming your variables/methods. Example: Avoid using getAge(), fetchName(), retrieveMail(). Instead, be consistent and name them getAge(), getName(), and getMail().
- Avoid slang, unclear abbreviations and disinformation (indicative of wrong data structure in the variable name, etc).
- Avoid comments that say the obvious or those which are misleading.
- Never comment out code, just remove.
- Use comments only when you want to provide licensing information, warnings or there is a need to provide API documentation.
- Use comments when code is difficult to grasp at a single sight and it would make it easier by providing some comments as explanations (e.g: regex).
- Properly format the code by adding blank lines to separate unrelated concepts and grouping similar/ related concepts together.
- Do not write an unreadably long line of code or name in a single line. Split them into multiple lines and use precise short names.
- Write functions with a minimum number of parameters.
- Keep your functions simple to read and understand without writing 100s of lines of code inside a single function. Instead, split into multiple short functions.
- Consider splitting of functions, but be sensible.
- Increase reusability and make code DRY (Don’t Repeat Yourself).
- Try not to mix different levels of abstraction in the function.
- Avoid unexpected side effects.
- Check if your function makes unit testing easier.
These are the takeaways that you can pretty much read in the blog posts. After reading the posts. I hope we can all answer the question above that Yes! We can write clean code with practice and tips provided in the blog posts.
I encourage you to read each post as he provides helpful examples and detailed steps/tips to implement writing clean code.
I'll surely get back to these posts as I write codes.
To God be the glory!