I have multiple JS classes in my project, and some of them are dependant on the others. Is it better to export from a module and use it as import in another module (or) create an instance of the class I need and use it as required(here I have an HTML file where I've included all the scripts I need)?
Am I missing any fundamental of export/import? Please feel free to correct.
PS: I'm using Node.js
Top comments (4)
I cannot give concrete recommendations here, but I find myself using these signals: Scrolling and File Switching.
If you find yourself scrolling and switching between files less often, you are more likely moving in the right direction.
This is fantastic advice. Easy to remember. Easy to implement.
For the longer answer, there are pros and cons for each.
The second method sounds to me like dependency inversion. Dependency inversion is one of the SOLID principles. It means that we would have a special module purely to instantiate our other modules and their dependencies. For example, in your question, we would import the two modules there, instantiate the first one, and then instantiate the second one while passing in the first instance as a dependency. E.g.
const secondModuleInstance = new SecondModule(firstModuleInstance);. That way our normal modules do not import and instantiate their dependencies directly.
Dependency injection is a way to automagically do dependency inversion. All the instantiations are done automagically for us and we just specify what dependencies everything has in some configuration file. An example package for this is InversifyJS.
Benefit of dependency inversion:
Cost of dependency inversion:
I recommend the programming first principles series (disclaimer: I wrote it) or popular books such as Clean Code and Code Complete.
Thank you for explaining in detail. I'll surely go through your series.