Import considered harmful

Klee Thomas - Oct 5 '20 - - Dev Community

The import (and require) statement is incredibly powerful. Being able to separate out code into multiple files and packages has allowed the TypeScript (and JavaScript) ecosystem to flourish. But... It's a two edged sword. Our code tends to over use it (I certainly was and I expect you are as well). This over use is leading to lower code quality and harder to maintain code bases.

I have come to believe that use of the import keyword to bring in concrete classes and function should be considered harmful.

Using the import statement to access classes and functions from another file couples these files together tightly. Coupling code together is always a risk, code that is coupled together has to change together. Decoupling code into components that have one reason to change is a key element ensuring that your code adheres to the Single Responsibility Principle (code should have one reason to change) and the Open Closed Principle (Classes/Functions should be open for extension but closed for modification). Use of import to bring code from one file into another file breaks both of these principles.

Seemingly contradictory is that keeping code in a single file and failing to split it out into individual files also violates the Single Responsibility and Open Closed Principles. Which means that the import keyword is required and important. What is key is how it should be used. It should be used sparingly and intentionally.

My preference is to use it at a high level near to where the application is initialised or a request is handled. From this point the imported code can be used to instantiate classes, and curry functions. These can than be composed together, passing in functionality that may have otherwise been accessed using this import keyword. This composition creates testable, extendable, components. Adjusting the functionality of these components is now a matter of changing what is passed into the component rather than modifying the code of the component.

TypeScript has made composition easier from a developer experience point of view than it was using standard JavaScript. TypeScript has given us the ability to know and enforce the structure of the code that is passed into a function by having that function depend explicitly on an interface or type definition. This makes it easier to open functions for extension by decomposing code into smaller child functions and extracting them into their own files.

Using the import keyword to bring in classes, functions and objects will bind your code together in a way that will lead to it being harder to maintain. To ensure that code is more maintainable restrict the use of import for classes, objects, and functions to one place. Using import to depend on types and interfaces throughout the code is encouraged.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player