Best Practices in Angular Application Development
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.
6. Use environment variables
Environment configurations in Angular allow us to declare variables that are specific to each environment. Development and production are the default environments. We can also add new variables to existing environment files or create new environments. We can keep API URLs and other sensitive credentials in environment configurations.
7. Naming conventions
Consistent naming enables efficient maintainability and readability. Angular style guide recommends pattern as feature.type.ts
. Seperate file names with dots and dashes. We can follow camel case when declaring classes.
8. Application structure
Our application’s code should be inside the src
directory. A good point to note from Angular style guide on structuring the application, “Locate code quickly, Identify the code at a glance, keep the Flattest structure you can, and Try to be DRY.”
Conclusion
Building applications is a never-ending endeavour, and there’s always space for improvement. This list of improvements is a nice place, to begin with.