Three tips for better and clean code
I'm responsible for the code review and analytics performance system at my current job, and I´ve seen some code that could be improved.
I wrote this article with the objective to share my knowledge and practice my English writing.
Before we start, I´d like to state it is my personal opinion based on my knowledge in CLEAN CODE, SOLID and a better way to write code, please feel free to share your point of view.
My current stack is Angular 6, JavaScript, TypeScript and ASP.NET CORE, maybe this doesn't apply for your case.
Be careful when use the ternary operator
The ternary operator can be great for some solutions, especially when we´ve to return some value. The main issues found when using a ternary that doesn't return any values or are used as void functions, for example:
The example above sets the title inside the ternary and before this returns the value again.
If you use the ternary with void functions your code won't be clean and will do an unnecessary process. A better and clean way to do it is to use the value as return as in the example below:
Boolean Functions
JavaScript can turn your code clean, it is applied when using a function or variable that needs to return a boolean value. Look at the example.
The better way and clean to do it is ex:
Use let and const variable declarable every you can
In both in JavaScript and in Typescript you can declare let or const in your variable, this makes your code more secure and easier to understand.
By using let you can limit your variable scope
By using let, you can limit your variable scope, saving memory and using this just when you need like the example below.
Declaring const will ensure that your code can´t change this variable
To be clear about your code, also use const when your variable can´t be changed, declaring const will ensure that your code can´t change this variable and also make your code explicit and easy to read.
Below you can see an example about an error when you try to change the value of a const variable.
Final Remarks
I hope you enjoyed this simple article, I will share more articles to train my JavaScript skills, clean code and to write English.
If you have any considerations about this, please let me know.
#cleancode #solid #typescript #angular