Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What's weird about it? In practice it just means writing classes which instead of newing things inside the constructor, allows them to be passed in by the caller.

This is a pretty fundamental aspect of polymorphism and composition.



> What's weird about it?

What I meant about weird was that OP's proposed "solution" to DI is to "do it manually", while the exact reason while we want DI in the first place is not to do it manually (or, in the way that I heard it most in my life, "to be able to change it without rebuilding")


> What I meant about weird was that OP's proposed "solution" to DI is to "do it manually", while the exact reason while we want DI in the first place is not to do it manually (or, in the way that I heard it most in my life, "to be able to change it without rebuilding")

No, the main reason we want DI is to change the behaviors based on what's passed. That's dependency injection. Framework passing the dependencies is automatic dependency injection and what I'm advocating against.


> No, the main reason we want DI is to change the behaviors based on what's passed.

but which behaviours are passed depend on something external to the system - config files, etc. - so you need something that gets the information from somewhere and instantiates the correct class - and trust me, you don't want to write

    Protocol proto = null;
    if(config == "protocolA")
      proto = new ProtocolA;
    else if(config == "protocolB")
      proto = new ProtocolB;
    else if(config == "protocolC")
      proto = new ProtocolC;
    else if(config == "protocolD")
      proto = new ProtocolD;
    else
      throw whatever;

    return new MyObjectWithDependencies(proto);
especially when your system supports >50 protocols, and your object also needs a logger which can itself be of 12 different kinds, a file accessor which can mmap or not according to configuration & os, etc etc


Imo, dependency injection frameworks are distinct to the concept of DI. They do not represent DI itself, which is just a design pattern.


Agree, it reduces boilerplate and prevents you from shooting yourself in the foot when it comes to writing testable code.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: