Posted by Harsh Soni | Last Updated: 15-Jan-19
Best Practice to Write a Clean and Maintainable Code
What is Clean code and why to write it carefully?
It is a consistent style of programming that makes your code easy to understand and write. A Developer mostly spends its time on solving the problem and once it is solved, you are done. But I think because of your code 'Works' you are not done.
A good developer when faces situation where they have to do something repetitively, will find a better solution to complete that task. So keeping a clean code technique will decrease the frequency of changes from code and the need to debug unnecessary things over and over.
Clean code is a DRY Code
DRY stands for “Don’t Repeat Yourself.” If you are writing a repetitive code at multiple places then it isn't a good practice. One way to easily check is to see the patterns in your code, If there is any then it is prime for DRYing.
Commenting is power to Clean Code
Always add comments to your code describing the actual need/complexity to add that code instead of defining the logic of your code. It happens sometimes that you write some code and comment it properly. After that, when you found a bug you went back and change the code & forgot to change your comment reflecting your new logic. So when some other person reads your comments it will take him to rabbit hole because they focused on your comments.
Naming in your Clean Code
A developer should give serious thought on naming the variables names, functions and even the filenames. Here are some points to consider before naming anything in your code
- Function or Boolean variables that return or has a boolean value should start with "is", "has" and "should".
- Name your functions according to what they do, not how they do. Because it may change someday and you shouldn't need to refactor your code.
- Follow the camel casing formula writing any variable and function name.
Here are some best practices to follow when architecting your applications.
Always follow the single responsibility principle which is to use small functions with the individual job and does it well. To make it simple breaking up complex components into many smaller ones will lead to a better code and testability
Don't impose internal requirements on the consumer of your code also use a single file to define your constants and other required packages.
Try to follow strict linting rules which will help in writing consistent code.