Search code examples
javascriptdependency-injectiontheorymodularization

Difference between javascript modularisation and dependency Injection


What 's the difference with the modularisation of a javascript code (with browserify by example) and the dependency injection?

Are they synonymes? Are the two going together? Or Am I missing some point?


Solution

  • Modularisation refers to breaking code into individual, independent "packages".
    Dependency injection refers to not hardcoding references to other modules.

    As a practical example, you can write modules which are not using dependency injection:

    import { Foo } from 'foo';
    
    export function Bar() {
        return Foo.baz();
    }
    

    Here you have two modules, but this module imports a specific other hardcoded module.

    The same module written using dependency injection:

    export function Bar(foo) {
        return foo.baz();
    }
    

    Then somebody else can use this as:

    import { Foo } from 'foo';
    import { Bar } from 'bar';
    
    Bar(Foo());
    

    You inject the Foo dependency at call time, instead of hardcoding the dependency.