Hello, today I am writing again and this time I am going to introduce you to how we incur in a very common code smell called Too Many Import, is caused by the abusive use of imports in components, classes or any other type of module of our project.
Cause
It seems like a very harmless Code Smell but it can indicate that we are breaking very important principles such as:
- Coupling
- Low cohesion
- Violation of the SRP (Single Responsibility Principle)
Example
In the following example we can see how up to 13 imports are carried out, which should lead us to think if our component does not have too many responsibilities:
Solutions
-
In the first place, it may seem a bit obvious, but we should review the use of these imports and assess if they are all essential for the correct functioning of the component.
-
As you can imagine, the solution to this involves separating responsibilities and dividing this component into several smaller ones or even extracting logic to hooks, although in this case, in order not to introduce many concepts, we will propose a solution based on dividing it into several smaller components:
FirstComponent
SecondComponent
ThirdComponent
Finally the ExampleComponent , it would stay like this:
We can see that we have reduced the number of import by a large number, but this does not end here, by making this division we are delegating the responsibilities to each component.
Warning!
Therefore, like every Code Smell, this one must be carefully analyzed before applying any solution, since a hasty decision can cause some side effects.
Not all are advantages, below we will see some disadvantages that we must consider when applying these splits:
-
In some cases we can incur in a premature optimization, especially in small projects that do not need much maintenance.
-
They can have many components, classes etc if the project has considerable dimensions.
Bonus Track
To help us take more into account the number of imports we can use our linter, for example in the case of using eslint we have a rule inside the eslint-plugin-import plugin called import/max-dependencies which we can configure to help us with this smell.
Thanks for reading me 😊