In this article, I’m going to explain some of the best practices in Angular application development that I’ve learnt and used in XmlToJson project.
1. Use const when the value is not going to be reassigned
When a variable is about to point to a constant reference always, we can simply put
const instead of
let . It helps to improve the code readability and throws a compile-time error when we mistakenly reassign a value.
2. Isolate API calls in service
We can put API calls service and invoke them in components where necessary. Whenever we need to change the logic of API calls, it’ll be easy to check out in that dedicated API service directory.
3. Always declare variables with type
We can declare variables with specific types other than
any . In this way, we can avoid bugs caused by missing types.
4. Small components
We can extract components into small and operates purely based on the inputs and outputs provided to it.
We should have only the display logic in components. If components need to have business logic such as data parser, API calls and conversions, we can put them into services and invoke them within the components. Any business logic can be extracted into its own services where appropriate.
5. Small methods
We can follow the single responsibility principle while defining methods. That is, a method will do only one specified task. Thus, we can define each method for specific tasks.
Let’s say if a method is responsible for a task but inside of it, there could be some other operations that could be happening. In that case, we can extract private methods for each of them.